EntityFrameWork 4.0相关
07-18 更新
ApplyCurrentValues 方法
原理是从指定的对象获取标量属性值,并拷贝它们到带有相同EntityKey的对象中去。任何与初始值不同的值将被标记为Modified
(我自己测试了下,是把自己改为Dettach,把带有相同EntityKey的对象Modify)
ApplyPropertyChanges 方法的使用,修改实体
使用ApplyPropertyChanges,可以使用不在集合中的实体覆盖到集合中主键对应用实体上
如果内存中没有主键对应的记录,会报错
Attach与ApplyPropertyChanges有类似之处,都是将Context集合外的[实体]与Context集合内的[实体]同步.
ApplyPropertyChanges调用时,要求对应的[实体]在内存中,Attach不要求
pplyPropertyChanges调用后,集合内的实体状态会标记为EntityState.Modified
Attach调用后不会修改合内的实体状态,如要SaveChanges(),要手动标记EntityState.Modified
ApplyPropertyChanges是用[外部实体]全覆盖Context集合中的[实体],
Attach方式,通过SetModifiedProperty()方法,可在调用SaveChanges()时,只修改只定有字段值
myContext context = new myContext();
myTab r1 = context.myTab.First(p => p.ID == 1);
myTab nr = myTab.CreatemyTab(1);
nr.a = "wxwinter";
Console.WriteLine(nr.EntityState); //print:Detached
Console.WriteLine(r1.EntityState); //print:Unchanged
context.ApplyPropertyChanges("myTab", nr);
myTab r2 = context.myTab.First(p => p.ID == 1);
Console.WriteLine(nr.EntityState); //print:Detached
Console.WriteLine(r2.EntityState); //print:Modified
context.SaveChanges();
//EntityKey
public bool DeletObj(string EntityName, int ObjID, out string ErrorMessage)
{
try
{
EntityKey ek = new EntityKey("WhtManagerEntities1." + EntityName, "id", ObjID);
object o = null;
if (ObjectContext.TryGetObjectByKey(ek, out o))
{
ObjectContext.AttachTo(EntityName, o);
ObjectContext.ObjectStateManager.ChangeObjectState(o, EntityState.Deleted);
ObjectContext.SaveChanges();
ErrorMessage = "";
return true;
}
ErrorMessage = "找不到实体";
return false;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return false;
}
}
{
try
{
EntityKey ek = new EntityKey("WhtManagerEntities1." + EntityName, "id", ObjID);
object o = null;
if (ObjectContext.TryGetObjectByKey(ek, out o))
{
ObjectContext.AttachTo(EntityName, o);
ObjectContext.ObjectStateManager.ChangeObjectState(o, EntityState.Deleted);
ObjectContext.SaveChanges();
ErrorMessage = "";
return true;
}
ErrorMessage = "找不到实体";
return false;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return false;
}
}