如何使用实体框架更新特定记录的一个字段? [英] How to update one field of specific records using Entity Framework?

查看:77
本文介绍了如何使用实体框架更新特定记录的一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新一个叫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();
    }

这篇关于如何使用实体框架更新特定记录的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆