如何使用实体框架更新特定记录的一个字段?
问题描述:
我想更新一个叫pejman的人的家庭。
这是我的对象类:
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; }
}
我的更新方法是:(在Program.cs中)
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?
编辑:假定我不知道某人的身份证,而我只知道某人的名字,有什么办法可以更新该人的家庭? p>
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?
答
创建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();
}