How to update only one field using Entity Framework?

前端 未结 16 1499
后悔当初
后悔当初 2020-11-22 09:09

Here\'s the table

Users

UserId
UserName
Password
EmailAddress

and the code..



        
16条回答
  •  攒了一身酷
    2020-11-22 09:32

    I'm late to the game here, but this is how I am doing it, I spent a while hunting for a solution I was satisified with; this produces an UPDATE statement ONLY for the fields that are changed, as you explicitly define what they are through a "white list" concept which is more secure to prevent web form injection anyway.

    An excerpt from my ISession data repository:

    public bool Update(T item, params string[] changedPropertyNames) where T 
      : class, new()
    {
        _context.Set().Attach(item);
        foreach (var propertyName in changedPropertyNames)
        {
            // If we can't find the property, this line wil throw an exception, 
            //which is good as we want to know about it
            _context.Entry(item).Property(propertyName).IsModified = true;
        }
        return true;
    }
    

    This could be wrapped in a try..catch if you so wished, but I personally like my caller to know about the exceptions in this scenario.

    It would be called in something like this fashion (for me, this was via an ASP.NET Web API):

    if (!session.Update(franchiseViewModel.Franchise, new[]
        {
          "Name",
          "StartDate"
      }))
      throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
    

提交回复
热议问题