2016-02-07 38 views
0

我試圖用Entity Framework開發我的第一個ASP.net MVC項目。我沒有使用任何視圖模型,我在視圖和數據庫事務中都使用了相同的模型。這是事情,我有自定義用戶表。在創作中,我的User模型中有5件東西:UserNameUserPassword,FullName, BranchBranchId(導航到其他表格)。但是,當我想編輯用戶時,我不需要UserPassword字段,因爲現在不能更改密碼。因此,我創建了一個與User型號相同的型號,但UserPassword字段名爲UserEdit將視圖模型複製到數據模型

在創建視圖我使用我的用戶模型,在編輯視圖中我使用UserEdit模型。在控制器中,我使用automapper並將User中的值複製到UserEdit,然後返回查看。它工作正常,問題是關於更新。

我試圖更新這樣的用戶:

public bool Update(UserEdit userEdit) { 
     User user = Find(userEdit.UserUsername); 

     Mapper.CreateMap<UserEdit, User>(); 

     user = (User)Mapper.Map(userEdit, user, typeof(UserEdit), typeof(User)); 

     if (_modelState.IsValid) 
     { 
      _transactionManager.GetContext().Entry(user).State = System.Data.Entity.EntityState.Modified; 
      _transactionManager.CommitTransaction(); 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

但它給我這個錯誤:

Additional information: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

當我檢查我試圖更新用戶,我看到它中的實體框架相關對象。所以我想這個錯誤的原因可能是關於分支表和用戶對象中的那些相關對象。我真的不需要我的用戶對象中的那些與實體相關的對象。如果我只能複製模型中的屬性,那就太好了。也許我在做別的事情。因爲我知道人們總是使用視圖模型,所以應該有一個簡單的方法來完成它。

任何想法?

謝謝

+0

無法在不看到模型(數據和視圖模型)的情況下提供幫助,但檢查所有屬性是否正在更新。 –

+0

其實我說的是我的模特是怎麼樣的,我的主模特只有5個領域,查看模特是一樣的,只有缺少密碼的領域。 – user3781428

+0

顯示它們和視圖(在視圖模型中使用'Branch'和'BranchID'是沒有意義的) –

回答

0

你真的不應該滾動自己的密碼認證。使用MVC內置的內容。也就是說,保存視圖模型最簡單的方法就是這樣;

using (YourContext db = new YourContext()) 
{ 
    User u = db.User.Find(userEdit.UserUsername); 
    db.Entity(u).State = System.Data.Entity.EntityState.Modified; 
    u.FullName = userEdit.FullName; 
    ....set the other properties here... 

    db.SaveChanges(); 
} 
+0

我可以做到這一點,但我認爲用automapper來做它會更好。 – user3781428

+0

Automapper引入了額外的複雜程度。它有它的位置,但是爲了映射5個域,我不會使用它。對於您的第一個項目,當您對模型有更好的理解時,請保持簡單,充分利用automapper。 –