问题
I have the following metadata:
var entityTypeParent = {
shortName: 'ParentItemType',
namespace: 'MyNamespace',
autoGeneratedKeyType: Identity,
defaultResourceName: 'ParentItemTypes',
dataProperties: {
id: { dataType: DT.Int32, isPartOfKey: true }
},
navigationProperties: {
users: {
entityTypeName: 'User',
isScalar: false,
associationName: 'ParentItem_User'
}
}
};
var entityTypeUser = {
shortName: 'User',
namespace: 'MyNamespace',
autoGeneratedKeyType: Identity,
defaultResourceName: 'Users',
dataProperties: {
loginName: { dataType: DT.String, isPartOfKey: true },
displayText: {},
parentItemId: {
dataType: DT.Int32
}
},
navigationProperties: {
agendaTask: {
entityTypeName: 'ParentItemType',
associationName: 'ParentItem_User',
foreignKeyNames: ['parentItemId']
}
}
};
In the UI I have a control (Kendo Multi-Select), which is bound to the ParentItemType.users property (AngularJS binding), which allows to select a user from a list (retrieved using breeze-kendo bridge and 'webApiOData' adapter).
Selecting a user results in an "Error: Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed." exception in setNpValue (https://github.com/Breeze/breeze.js/blob/397b2a02aa2173175c304eb1b37332f1656db6f5/src/a35_defaultPropertyInterceptor.js#L287).
If I change the definition to isScalar eq true. I get an exception at https://github.com/Breeze/breeze.js/blob/397b2a02aa2173175c304eb1b37332f1656db6f5/src/a35_defaultPropertyInterceptor.js#L298
context.newValue is an array of user entities.
Is this an error somewhere in my metadata definition? Actually I just want to have multiple users in my ParentItem.
Breeze Version: 1.5.4
回答1:
No, that's not an error in your metadata definition. This is by design. Nonscalar navigation properties are managed by Breeze. Multi-select controls try to take ownership of the value array and replace it with a new array. Breeze won't allow that because it would be catastrophic and break your entities.
Multi-select controls are a bit of a pain. You need to leverage the events that the control triggers to update the navigation property when the user makes a selection and manually create the association entities from the selected values and delete them if the user unselects them. I don't have an example for KendoUI, but FWIW, here is an Angular2 example for the DevExpress TagBox and the following entity model.
Model(Subject) 1<--->n SubjectVehicleAssociation n<--->1 LookupItem(Vehicle)
There's a bit of work involved. The multi-select controls out of the box only work with basic arrays.
<dx-tag-box [dataSource]="adapter.dataSource"
displayExpr="description"
[value]="adapter.value"
[searchEnabled]="true"
(onSelectionChanged)="adapter.selectionChanged($event)">
</dx-tag-box>
Adapter instance creation in the component:
let valueConverter: ITagBoxValueConverter<SubjectVehicleAssociation, { code: string, longValue: string }> = {
match: (item: SubjectVehicleAssociation, lookupItem: { code: string, longValue: string }) => item.abbreviation === lookupItem.code,
seed: (item: SubjectVehicleAssociation, lookupItem: { code: string, longValue: string }) => {
item.description = lookupItem.longValue;
item.abbreviation = lookupItem.code;
return item;
}
};
this.adapter = new TagBoxAdapter(SubjectVehicleAssociation,
() => Promise.resolve(this.vehicleAssociationsLookup),
this.modelSubjectVehicleRelation,
'associations',
valueConverter);
And the Adapter implementation:
import DataSource from 'devextreme/data/data_source';
import * as _ from 'lodash';
import { Entity, EntityState } from 'breeze-client';
export interface ITagBoxValueConverter<T extends Entity, W> {
match(value1: T, value2: W): boolean;
seed(target: T, source: W): T;
}
export class TagBoxAdapter<T extends Entity, W> {
dataSource: DataSource;
constructor(private itemType: { new (): T },
private data: (searchValue?: string, maxSearchResults?: number) => Promise<W[]>,
private model: any,
private valueExpr: string,
private valueConverter: ITagBoxValueConverter<T, W>,
private maxSearchResults: number = 20) {
this.initializeDataSource();
}
get value(): T[] {
return _.get<T[]>(this.model, this.valueExpr, []);
}
selectionChanged(e: { addedItems: T[], removedItems: T[] }) {
e.addedItems.forEach(item => {
if (item.entityAspect && item.entityAspect.entityState.isDeleted()) {
// Real entity, needs to be resurrected
item.entityAspect.rejectChanges();
} else {
// Placeholder entity, needs to be attached first
this.model.entityAspect.entityManager.attachEntity(item, EntityState.Added);
this.value.push(item);
}
})
e.removedItems.forEach(item => {
item.entityAspect.setDeleted();
})
};
private initializeDataSource() {
let sourceData = (searchValue: string, maxSearchResults: number) => {
return this.data(searchValue, maxSearchResults).then((results) => {
return results.map(dataItem => {
// Find existing association entity if exists
let item = _.find(this.value, item => this.valueConverter.match(item, dataItem));
if (item) return item;
// Not associated yet, return placeholder association entity
return this.valueConverter.seed(new this.itemType(), dataItem);
})
});
};
this.dataSource = new DataSource({
// The LoadOptions interface is defined wrong it's lacking the search properties
load: (loadOptions: any) => {
let searchValue = loadOptions.searchValue ? loadOptions.searchValue : "";
return sourceData(searchValue, this.maxSearchResults).then(data => data.filter(item => !_.intersection(this.value, [item]).length));
},
byKey: (key) => {
return sourceData(key, 1).then((data) => _.find(data, key));
}
});
}
}
来源:https://stackoverflow.com/questions/41148572/breezejs-nonscalar-navigation-properties-are-readonly