我有一个微风控制器,它在客户端未提交的保存更改期间添加一个实体。
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
if (entityInfo.Entity.GetType() == typeof(User))
{
if (entityInfo.EntityState == EntityState.Added)
{
User user = entityInfo.Entity as User;
OrganizationUser orgUser = new OrganizationUser()
{
Enabled = true,
OrganizationId = User.OrgId,
User = user
};
user.OrganizationUsers.Add(orgUser);
}
return true;
}
throw new InvalidOperationException("You can not use this service to modify an entity of type: " + entityInfo.Entity.GetType().Name);
}
当返回响应时,客户端微风管理器将服务器端添加对象的状态设置为“已添加”。上面的 OrganizationUser 对象最终在客户端上具有已添加状态。然后在下一个 SaveChanges 中提交。这是一个错误吗?
这是第一次保存的响应:
{
"$id": "1",
"$type": "Breeze.WebApi.SaveResult, Breeze.WebApi",
"Entities": [{
"$id": "2",
"$type": "LeonardoMD.Server.Api.Security.Admin.User, LeonardoMD.Server",
"Id": 9176,
"Email": "SearchProviderA@leonardoMD.com",
"FirstName": "SearchProviderA",
"LastName": "SearchProviderA",
"OrganizationUsers": [{
"$id": "3",
"$type": "LeonardoMD.Server.Api.Security.Admin.OrganizationUser, LeonardoMD.Server",
"UserId": 9176,
"User": { "$ref": "2" },
"OrganizationId": 421,
"Enabled": true
}]
}],
"KeyMappings": [{
"$id": "4",
"$type": "Breeze.WebApi.KeyMapping, Breeze.WebApi",
"EntityTypeName": "LeonardoMD.Server.Api.Security.Admin.User",
"TempValue": -1,
"RealValue": 9176
}]
}
这是第二次保存的提交:
{
"entities": [{
"Id": -2,
"CreateDate": null,
"CreateUserId": null,
"ModifyDate": null,
"ModifyUserId": null,
"Email": "SearchProviderB@leonardoMD.com",
"FirstName": "SearchProviderB",
"LastName": "SearchProviderB",
"BirthDate": null,
"GenderId": null,
"AddressLine1": null,
"AddressLine2": null,
"City": null,
"State": null,
"StateId": null,
"PostalCode": null,
"CountryId": null,
"DayPhone": null,
"DayPhoneExtension": null,
"Password": null,
"SecretQuestion": null,
"SecretAnswer": null,
"Enabled": null,
"AcceptTermsDate": null,
"entityAspect": {
"entityTypeName": "User:#LeonardoMD.Server.Api.Security.Admin",
"defaultResourceName": "Users",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": {
"propertyName": "Id",
"autoGeneratedKeyType": "Identity"
}
}
},
{
"UserId": 9176,
"OrganizationId": 421,
"Enabled": true,
"entityAspect": {
"entityTypeName": "OrganizationUser:#LeonardoMD.Server.Api.Security.Admin",
"defaultResourceName": "OrganizationUsers",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": null
}
}],
"saveOptions": {}
}
请注意,第二个实体是在先前保存更改的响应中返回的实体。它的 entityState 设置为已添加。
我有一个解决方法,但它很脆弱,需要针对服务器在保存后返回新实体的每种情况进行特殊编写。有没有办法将 Breeze 设置为在从服务器返回的所有新实体上接受更改作为对 saveChanges 调用的响应?
manager.saveChanges()
.then(function (saveResult) {
$.each(saveResult.entities, function (i, entity) {
if (entity.organizationUsers && entity.organizationUsers().length > 0)
$.each(entity.organizationUsers(), function (index, orgUser) {
orgUser.entityAspect.acceptChanges();
});
entity.entityAspect.acceptChanges();
});
dfd.resolve();
})
.fail(function (error) { _this.handleError(context, promise, error); });