且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用实体框架更新特定记录的一个字段?

更新时间:2023-11-09 22:07:58

创建Person对象的实例时,您缺少一个ID字段。由于这个实体框架无法找到现有的人。

You are missing an Id field when creating an instance of Person object. Because of this Entity Framework is not able to find an existing Person.

您的代码应如下所示:

public static void Update(int id, string name, string family)
{
    var _person = new Person() { Id = id , FirstName = name, LastName = family };

    using (var newContext = new MyDbContext())
    {
        newContext.Persons.Attach(_person);
        newContext.Entry(_person).Property(X => X.LastName).IsModified = true;
        newContext.SaveChanges();
    }