我是第一次实施实体框架。我正在使用添加/更新具有父属性的对象。
我知道实体的父实体被初始化为“null”。我没有完全理解如何使用父实体与父实体引用字段,或者将更改保存到实体所需的内容。
实体:null
EntityReference:not null
实体:不为空 EntityReference:null
实体:不为空 EntityReference:not null
感谢您的帮助。
代码示例:
internal void AddUpdateObject(MyDataContext context)
{
// HOW DO I HANDLE THIS SECTION vvvv
if (this.MyParentEntity == null)
{
throw new Exception("Parent Property Null.");
}
if (this.MyParentEntity.EntityState == EntityState.Detached)
{
MyParentEntity t = this.MyParentEntity;
this.MyParentEntity = null;
context.AttachTo("ParentCollection", t);
this.MyParentEntity = t;
}
// ^^^^^^^^^
try
{
context.AddToMyEntities(this);
}
catch (InvalidOperationException)
{
// the object with the key already exists
MyEntity ent = context.MyEntities.First(x => x.id == this.id);
PropertyInfo[] props = typeof(MyEntity).GetProperties();
foreach (PropertyInfo pi in props)
{
if (pi.CanRead && pi.CanWrite &&
!pi.PropertyType.Name.StartsWith("EntityCollection") &&
!pi.Name.Equals("id"))
pi.SetValue(ent, pi.GetValue(this, null), null);
}
}
}
答案 0 :(得分:0)
您可以执行以下操作:
var entity = context.MyEntities.FirstOrDefault(x => x.id == this.id);
if (entity != null)
{
// updating
// HOW DO I HANDLE THIS SECTION vvvv
if (!entity.MyParentEntityReference.IsLoaded)
{
entity.MyParentEntityReference.Load();
}
}
else
{
// inserting
entity = this;
context.AddToMyEntities(this);
this.ParentEntity = // whatever
}
entity.SomeOtherProperty = someValue;
context.SaveChanges();
这会回答你的问题吗?
答案 1 :(得分:0)
这是有用的:
MyEntity e = context.MyEntities.FirstOrDefault(x => x.id == this.id);
if(e == null){
MyParent p = this.Parent;
this.Parent = null;
context.Attach(p);
this.Parent = p;
}
else
{
context.ApplyPropertyChanges("MyEntities", this);
}
一些参考链接:
ApplyPropertyChanges
Adding objects with references to other objects