静默忽略实体框架更新

时间:2010-11-16 18:07:18

标签: entity-framework

我通过WCF服务检索停留并将其传递到前端。用户更新该对象上的数据,然后将其传递回WCF服务。

以下代码可以正常添加新的停留,但它会默默地忽略更新。我错过了什么?

public void UpdateStay(ResidentDataTypes.Stay stay)

    {
        using (ResidentDataTypes.ResidentEntities entity = new ResidentDataTypes.ResidentEntities())
        {
            if (stay.StayId == Guid.Empty)
            {
                entity.Stay.AddObject(stay);
            }
            else
            {
                entity.Stay.ApplyChanges(stay);
            }
            entity.SaveChanges();
        }
    }

2 个答案:

答案 0 :(得分:1)

当您的对象从WCF序列化时,它们处于Detached状态,EF不会为它们生成更新语句。你有2个选择:

1.从数据库中获取相同的对象,然后执行ObjectSet.ApplyCurrentValues:

using (ResidentDataTypes.ResidentEntities context = new 
                                            ResidentDataTypes.ResidentEntities())
{
    if (stay.StayId == Guid.Empty)
    {
        context.Stay.AddObject(stay);
    }
    else
    {
         // Fetch the Stay object into the cache:
         context.Stay.First(s => s.StayId == stay.StayId);

         // Now ApplyCurrentValues from the stay object coming from WCF:
         context.Stay.ApplyCurrentValues(stay);
    }
    entity.SaveChanges();
}


2.手动将Detached状态更改为Modified:

using (ResidentDataTypes.ResidentEntities context = new 
                                            ResidentDataTypes.ResidentEntities())
{
    if (stay.StayId == Guid.Empty)
    {
        context.Stay.AddObject(stay);
    }
    else
    {        
        // Attach the stay object coming from WCF to ObjectContext:
        context.Stay.Attach(stay);

        // The attached object is going into Unchanged mode after attaching 
       // so we need to change the state to Modified:
        context.ObjectStateManager.ChangeObjectState(stay, EntityState.Modified);
     }
     entity.SaveChanges();
}

答案 1 :(得分:0)

我认为您必须使用类似

的内容将您的实体附加到您的上下文中
entity.Attach(stay)