Entity Framework DbContext对一个Entity 进行更新。


一、更新实体:

EF的DbContext可以实现对一个对象进行更新,而不需要再一次将对象读入内存进行修改,而是采用Attach的方式。

Student stud ;
    // Get student from DB
    using (var ctx = new SchoolDBEntities())
    {
        stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault();
    }

    // change student name in disconnected mode (out of DBContext scope)
    if (stud != null)
    {
        stud.StudentName = "Updated Student1";
    }

    //save modified entity using new DBContext
    using (var dbCtx = new SchoolDBEntities())
    {
        //Mark entity as modified: 这里采用entity的主键进行匹配。因此,采用这种方法时,必须确保主键已经设置。
        dbCtx.Entry(stud).State = System.Data.EntityState.Modified;    
        dbCtx.SaveChanges();
    }
二、添加或者是更新实体
对一个实体,如果尚未存在于数据库,我们的更新将会失败。所以,大多数情况我们得先去访问数据库,判断是否可以更新。而EF有提供一个新的方法。如果一个实体不存在,就添加;否则更新。具体如下:
dbCtx.Students.AddOrUpdate(stud);

    另外,我还没有发现如何对Related的Entity进行更新的方式,特别是Collection,目前我采用的是直接设置相关的Entity的状态为Modified。请知道的大神指点一下。


相关参考:

http://stackoverflow.com/questions/19322532/updating-a-detached-entity-in-entity-framework-with-related-entites

http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx

http://stackoverflow.com/questions/18274408/entity-framework-update-method-to-object-with-collection

http://codereview.stackexchange.com/questions/37304/update-only-modified-fields-in-entity-framework

添加或者是更新:http://stackoverflow.com/questions/10075495/add-or-update-an-entity-without-knowing-if-its-exists





你可能感兴趣的:(Entity,FrameWork)