我对这个 EF 很陌生,但我认为我正在取得进展。无论如何,看来我不知道如何更新与外键相关的对象。
我的 DbRelation 是:
我正在尝试更新一个成员 LANGUAGEID,这是我调用的上下文:
public class ManagerBase
{
private static NoxonEntities _entities = null;
public NoxonEntities Entities
{
get
{
if (_entities == null)
_entities = new NoxonEntities();
return _entities;
}
}
}
我尝试过很多事情。这是一个:
1)
MemberManager currentMemberManager = new MemberManager();
var Mem = currentMemberManager.MyEntities.Member.SingleOrDefault(c => c.Id == 2);
var Lang = currentLanguageManager.Entities.Language.SingleOrDefault(c => c.Id == 1);
Mem.Language = Lang;
//Or
Mem.LanguageId = Lang.Id;
currentMemberManager.Save(Mem);
在appreach 1中,我收到一个错误,例如
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
2)
//Managers uses ManagerBase class as a Base class
MemberManager currentMemberManager = new MemberManager();
currentMemberManager.Save(Globals.CurrentMember.Id, Globals.CurrentLanguage.Id);
//These Global objects coming from a Http Session
//You may also say not to keep whole member object in session which I'll not after I figure this out
Here is my SAVE method and where I have the actual problem:
public void Save(Member entity)
{
var Data = base.Entities.Member.First(c => c.Id == entity.Id);
if (Data != null)
{
Data = entity;
base.Entities.SaveChanges();
}
}
}
在 appreach 1 中,我在 EF 模型 edmx 文件中的此代码中出现错误
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 LanguageId
{
get
{
return _LanguageId;
}
set
{
OnLanguageIdChanging(value);
ReportPropertyChanging("LanguageId");
_LanguageId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("LanguageId");
OnLanguageIdChanged();
}
}
错误是
Object reference not set to an instance of an object.
显然,我对 EF 的态度是错误的。
您能否帮助我并展示如何正确更新关系 ID (ForeignKeyId) ?
非常感谢。