我試圖用Entity Framework開發我的第一個ASP.net MVC項目。我沒有使用任何視圖模型,我在視圖和數據庫事務中都使用了相同的模型。這是事情,我有自定義用戶表。在創作中,我的User
模型中有5件東西:UserName
,UserPassword
,FullName
, Branch
和BranchId
(導航到其他表格)。但是,當我想編輯用戶時,我不需要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.
當我檢查我試圖更新用戶,我看到它中的實體框架相關對象。所以我想這個錯誤的原因可能是關於分支表和用戶對象中的那些相關對象。我真的不需要我的用戶對象中的那些與實體相關的對象。如果我只能複製模型中的屬性,那就太好了。也許我在做別的事情。因爲我知道人們總是使用視圖模型,所以應該有一個簡單的方法來完成它。
任何想法?
謝謝
無法在不看到模型(數據和視圖模型)的情況下提供幫助,但檢查所有屬性是否正在更新。 –
其實我說的是我的模特是怎麼樣的,我的主模特只有5個領域,查看模特是一樣的,只有缺少密碼的領域。 – user3781428
顯示它們和視圖(在視圖模型中使用'Branch'和'BranchID'是沒有意義的) –