Update a single property of a record in Entity Framework Code First

后端 未结 3 904
迷失自我
迷失自我 2020-12-30 03:33

How can I update a single property of a record without retrieving it first? I\'m asking in the context of EF Code First 4.1

Says I have a class User

3条回答
  •  Happy的楠姐
    2020-12-30 04:32

    I'm actually dealing with this right now. What I decided to do was override the ValidateEntity method in the DB context.

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary items)
    {
        var result = base.ValidateEntity(entityEntry, items);
    
        var errors = new List();
    
        foreach (var error in result.ValidationErrors)
        {
            if (entityEntry.Property(error.PropertyName).IsModified)
            {
                errors.Add(error);
            }
        }
    
        return new DbEntityValidationResult(entityEntry, errors);
    } 
    

    I'm sure there's some holes that can be poked in it, but it seemed better than the alternatives.

提交回复
热议问题