我试图用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'是没有意义的) –