简体   繁体   English

在实体框架中使用AttachTo不起作用

[英]Using AttachTo in Entity Framwork Not Working

I have a generic CRUD repository that attaches an updated object to the ObjectContext using AttachTo as below: 我有一个通用的CRUD存储库,它使用AttachTo将更新的对象附加到ObjectContext,如下所示:

NB the property entitySetName supplies the name of the table the object is being attached to 注意, entitySetName属性提供对象附加到的表的名称

    public virtual void Save(TModel t)
    {
            TModel unboxed = (TModel)t;
            db.AttachTo(entitySetName, unboxed);
            db.SaveChanges();
    }

No errors show up, just doesnt save the data. 没有错误显示,只是不保存数据。 Can anyone see why? 谁能看到原因?

AttachTo adds an entity to the context in state Unchanged . AttachTo将状态为Unchanged的实体添加到上下文中。 When you call SaveChanges immediately after that nothing gets updated because - from EF perspective - the entity is "unchanged". 在此之后立即调用SaveChanges ,没有任何更新,因为-从EF角度来看-实体是“不变的”。

You need to set the state to Modified to tell EF that properties have changed and should be written to the database: 您需要将状态设置为“已Modified以告知EF属性已更改,应将其写入数据库:

public virtual void Save(TModel t)
{
        TModel unboxed = (TModel)t;
        db.AttachTo(entitySetName, unboxed);
        db.ObjectStateManager.ChangeObjectState(unboxed, EntityState.Modified);
        db.SaveChanges();
}

I believe you want to modify by a single column. 我相信您想通过单个列进行修改。 You can try the .Attach . 您可以尝试.Attach

    public virtual void Save(TModel t)
    {
        db.SystemUserLogs.Attach(t);
        //db.Entry(t).State = EntityState.Modified; //<--- For whole fields modifier

        db.Entry(t).Property(x => x.entitySetName).IsModified = true; //<--- For one field modifier
        db.SaveChanges();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM