我们最近将软件升级到.NET 4.0和EF 4.0(没有自我跟踪实体)(以前的.NET 3.5 SP1)。现在,在以前的工作代码中引发了一个新的异常,我们不明白。
我们有一个名为Resident的实体,另一个名为ResidentExtension的实体,它将已经很大的Resident实体扩展为1到(0/1)的关系。以下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,
};
在此声明后直接引发以下异常:
违反了多重性约束。关系的“ResidentExtensions”角色VOCURA.EntityDataModels.EvocuraCarehomeManagementEntityModel.FK_ResidentExtensions_Residents'具有多重性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;
}
}
我发现的唯一解决方案是首先提交没有扩展名的Resident实体,然后创建ResidentExtension并设置外键(ResidentID)并将其添加到上下文并再次提交。但这不是它以前的工作方式。
有谁知道如何让这项工作再次成为现实?
答案 0 :(得分:1)
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;
总结一下,由于Resident实体与ResidentExtensions有1 - 0,1的关系;如果右边是0;只需将ResidentExtensions属性保留为null;否则初始化一个正确的ResidentExtensions对象并设置相关属性。