2016-02-07 40 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。 –