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

c# entity-framework

Question

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 FirstName { get; set; }
    public string LastName { get; set;}
    public DateTime BirthDate { get; set; }
    public bool IsMale { get; set; }
    public byte[] Image { get; set; }
    public byte[] RowVersion { get; set; }
    public virtual Person Parent { get; set; }
    public virtual ICollection<PhoneNumber> PhoneNumber { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual PersonInfo PersonInfo { get; set; }
}

and my method for updating is: (in Program.cs)

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

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

but it doesn't work! what is the problem?

EDIT: assume that i don't know person's Id, and i just know person's name, is there any way to update person's family?

1
17
5/24/2017 1:05:15 PM

Accepted Answer

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();
    }
25
5/24/2017 1:06:13 PM

Popular Answer

For resolving this error i got values by ID from database stored in Var Temprc. Then updated the field Password which i wont to update. Then attached temprc to my Userregistrations model. Then Marked PasswordConfirm isModified. then Savechanges();

using (var db = new Entities())
                {                       
                    var temprc = _reg.GetUserByID(Convert.ToInt32(Session["LogedUserID"]));
                    temprc.PasswordConfirm = U.NewPassword;
                    db.Userregistrations.Attach(temprc);
                    db.Entry(temprc).Property(x => x.PasswordConfirm).IsModified = true;
                    db.SaveChanges();    
                }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow