2013-09-27 39 views
1

我正在用C#和Entity Framework Code First開發一個WCF Rest服務。DbEntityValidationException:是否必須發送所有必填字段以僅更新一個?

我有一個表User有10列,但是這是需要的列JSON表示:

{ 
    "Name": "user_1", 
    "Active": true, 
    "Gender": 1, 
    "Email": "[email protected]", 
    "Birthday": "02/07/1971", 
    "City": "city_1", 
    "Country": "country_1" 
} 

這是我如何使用Entity Framework Code First更新User

private User InsertOrUpdateUser(User user) 
{ 
    try 
    { 
     using (var context = new MyContext()) 
     { 
      context.Entry(user).State = user.UserId == 0 ? 
              EntityState.Added : 
              EntityState.Modified; 
       context.SaveChanges(); 
     } 
    } 
    catch (Exception ex) 
    { 
     ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError; 
     ctx.SuppressEntityBody = true; 
    } 

    return user; 
} 

當我發送此用戶:

{ 
    "Name": "user_1-mod", 
    "UserId": 1 
} 

我得到以下錯誤:

[System.Data.Entity.Validation.DbEntityValidationException] = 
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."} 

我一定要送所有必填字段只有一個更新?

回答

1

沒有,

你並不需要在所有領域進行發送。 您可以使用此代碼(當然是有調整)

在我的通用庫,我做這個

DbSet dbSet = Context.Set<TEntity>(); 
dbSet.Attach(entity); 
Context.Entry<TEntity>(entity).Property(e => e.YourPropertyName).IsModified = true; 
Context.SaveChanges() 

這是說只有屬性被修改,將不嘗試更新的其餘部分。如果列的數量隨着每個請求而改變,則需要編寫一些邏輯來滿足這個要求。

的奇妙之處在於該行

Context.Entry<TEntity>(entity).Property(e => e.YourPropertyName).IsModified = true; 

也可用於像

Context.Entry<TEntity>(entity).Property("YourPropertyName").IsModified = true;