我们最近将我们的软件升级到了.net 4.0和ef4.0(没有自我跟踪实体)(以前的.net 3.5sp1)。现在,在以前的工作代码中出现了一个新的异常,这是我们无法理解的。
我们有一个名为resident的实体,还有一个名为residentextension的实体,它用1到(0/1)的关系扩展了已经很大的resident实体。以下C代码在我们的应用程序中生成一个新实体:
Residents resident = new Residents()
{
IsNewResident = true,
ResidentImage = Settings.Default.ResidentCardDefaultMaleImage,
IsActive = true,
ResidentCanBeDeleted = true,
ResidentExtensions = new ResidentExtensions(),
ResidentMasterDataState = EvoState.Error,
ResidentBasicDataState = EvoState.Error,
ResidentBenefactorsDataState = EvoState.Error,
};
此语句之后直接引发以下异常:
违反多重性约束。关系vocura.entitydatamodels.evocuracareHomeManagementEntityModel.fk“residentextensions”的角色“residentextensions”具有多重性1或0..1。
它出现在生成代码的setter中:
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("EVOCURA.EntityDataModels.EvocuraCarehomeManagementEntityModel", "FK_ResidentExtensions_Residents", "ResidentExtensions")]
public ResidentExtensions ResidentExtensions
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<ResidentExtensions>("EVOCURA.EntityDataModels.EvocuraCarehomeManagementEntityModel.FK_ResidentExtensions_Residents", "ResidentExtensions").Value;
}
set
{
((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<ResidentExtensions>("EVOCURA.EntityDataModels.EvocuraCarehomeManagementEntityModel.FK_ResidentExtensions_Residents", "ResidentExtensions").Value = value;
}
}
我找到的唯一解决方案是先提交不带扩展的常驻实体,然后通过设置外键(residentid)创建resident extension并将其添加到上下文中,然后再次提交。但这不是以前的工作方式。
有人知道怎么让这件事重蹈覆辙吗?
最佳答案
ResidentExtensions = new ResidentExtensions(),
我想这条线根本不需要。您正在创建一个新的驻留扩展对象,该对象没有任何主键,并且不存在于数据库中。当上下文试图保存residentextensions时,由于未设置任何属性,因此无法保存,这可能会导致数据库中与不可为空字段相关的某些异常。我认为你需要做的是:
Residents resident = new Residents()
{
IsNewResident = true,
ResidentImage = Settings.Default.ResidentCardDefaultMaleImage,
IsActive = true,
ResidentCanBeDeleted = true,
ResidentMasterDataState = EvoState.Error,
ResidentBasicDataState = EvoState.Error,
ResidentBenefactorsDataState = EvoState.Error,
};
//Now you need to either initialize a residentextextensions entity
// with proper values, or just do not relate it with the resident entity.
ResidentExtensions temp = new ResidentExtensions();
temp.PropertyA = 3;
//etc.
resident.ResidentExtensions = temp;
总而言之,由于常驻实体与residentextensions有1-0,1关系;如果右侧为0,则只保留residentextensions属性为空;否则初始化适当的residentextensions对象并设置相关属性。