How to update one field of specific records using Entity Framework?

前端 未结 6 1391
别跟我提以往
别跟我提以往 2021-01-31 11:10

I want update family of a person who his name is pejman. This is my object Class:

public class Person
{
    public int Id { get; set; }
    public string FirstNa         


        
6条回答
  •  太阳男子
    2021-01-31 11:33

    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.

    Your code should look like this:

    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();
        }
    

提交回复
热议问题