如何使用Entity Framework更新特定记录的一个字段?

时间:2014-01-25 12:57:14

标签: c# entity-framework

我想要更新他的名字是pejman的人的家庭。 这是我的对象类:

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中)

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

但它不起作用!有什么问题?

编辑:假设我不知道人的身份证,我只知道别人的姓名,有没有办法更新此人的家人?

6 个答案:

答案 0 :(得分:23)

创建Person对象的实例时,您缺少Id字段。由于此Entity Framework无法找到现有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();
    }

答案 1 :(得分:2)

  

编辑:假设我不知道人的身份证,我只知道别人的姓名,有没有办法更新此人的家人?

我假设FirstName类的Person字段包含此人的姓名,更新此人的姓氏意味着更新LastName字段。

第一步是让所有Person条记录FirstName等于该人的名字,让我们说它是“pejman”,所以代码如下所示。

var personsToUpdate = newContext.Persons.Where(o => o.FirstName == "pejman");

下一步是枚举personsToUpdate并将LastName属性设置为您想要的姓氏,然后调用.SaveChanges()的{​​{1}}方法将更改提交给数据库。假设您要将此人的姓氏更新为“MyFamilyName”,代码如下所示

DbContext

以下是使用foreach (Person p in personsToUpdate) { p.LastName = "MyFamilyName"; } newContext.SaveChanges(); Update参数的name方法的修改代码。

family

答案 2 :(得分:2)

为了解决这个错误,我从存储在Var Temprc中的数据库中获取了ID。 然后更新了我不会更新的字段密码。 然后将temprc附加到我的Userregistrations模型。 然后Marked PasswordConfirm被修改。 然后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();    
                }

答案 3 :(得分:0)

假设您有数据库可以找到的Person实例(如PawełBejger所述):

public class Person
    {
        /// <summary>
        /// USAGE: await UpdateDbEntryAsync(myPerson, d => d.FirstName, d => d.LastName);
        /// </summary>
        async Task<bool> UpdateDbEntryAsync<T>(T entity, params Expression<Func<T, object>>[] properties) where T : class
        {
            try
            {
                var db = new RtTradeData.Models.ApplicationDbContext();
                var entry = db.Entry(entity);
                db.Set<T>().Attach(entity);
                foreach (var property in properties)
                    entry.Property(property).IsModified = true;
                await db.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// The idea is that SomeFunction already has the instance of myPerson, that it wants to update.
        /// </summary>
        public void SomeFunction()
        {
            myPerson.FirstName = "Another Name"; myPerson.LastName = "NewLastName";
            UpdateDbEntryAsync(myPerson, d => d.FirstName, d => d.LastName);
        }
        /// <summary>
        /// Or directly requesting the person instance to update its own First and Last name...
        /// </summary>
        public void Update(string firstName, string lastName)
        {
            FirstName = "Another Name"; LastName = "NewLastName";
            UpdateDbEntryAsync(this, d => d.FirstName, d => d.LastName);
        }

        Person myPerson = new Person { PersonId = 5, FirstName = "Name", LastName = "Family" };
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

另见update a single field in Entity FrameworkEntity Framework update single

答案 4 :(得分:-2)

以下对我有用:

public ActionResult ChangePassword(Account account)
{
    try
    {
            if (ModelState.IsValid)
            {
                db.Accounts.Attach(account);
                db.Entry(account).Property(x => x.Password).IsModified=true;
                db.Configuration.ValidateOnSaveEnabled = false;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
    {
        Exception raise = dbEx;
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                string message = string.Format("{0}:{1}",
                    validationErrors.Entry.Entity.ToString(),
                    validationError.ErrorMessage);
                raise = new InvalidOperationException(message, raise);
            }
        }
        ModelState.AddModelError("", raise);

    } 
    return View(account);
}

答案 5 :(得分:-2)

任何对象这使得更新更容易。

using (var db = new DBContext())
        {
            AppUser au = new AppUser()
            {
                AppUserId = (int)txtID.Content,
                UserName = txtUserName.Text,
                Password = txtPwd.Password.ToString(),
            db.Entry(au).State= EntityState.Modified;
            db.SaveChanges();
        }