【发布时间】:2012-04-30 02:24:19
【问题描述】:
我的代码看起来很简单:
bool rv = false;
var results = from user in Users
where user.userName.Equals(newUser.userName)
select user;
if (results.Count() == 0)
{
this.context.Users.Add(newUser);
this.context.SaveChanges();
rv = true;
}
return rv;
但这会导致 DbEntityValidationException 带有一个内部异常值:
OriginalValues cannot be used for entities in the Added state.
...这是什么意思?我唯一能想到的是newUser 显示userID 的值为0,即使它有一个私有设置器并且userID 作为主键应该是数据库生成的。但如果 那 是问题所在,就不可能简单地使用 Add() 将对象插入任何 EF 数据库。所以我很困惑。
提前感谢任何可以帮助阐明这一点的人。
ETA:newUser 由我的 Controller 中的以下代码创建:
[HttpPost]
public ActionResult CreateRegistration(FormVMRegistration newRegistration)
{
//draw info from form and add a new user to repository
User newUser = new User();
newUser.userName = newRegistration.userName;
newUser.screenName = newRegistration.screenName;
newUser.password = newRegistration.usersPW;
bool addSuccess = userRep.Add(newUser);
...
}
FormVMRegistration 只是一个只有字符串属性的 ViewModel,用于将数据从注册表单传送到控制器。
userRep 是我的用户存储库。
【问题讨论】:
-
UserId 不应该真的有一个私有设置器,因为 EF 会尝试在保存时将其值放入此属性中。这应该是公开的
-
在此之前创建 newUser 的代码是什么?
-
@Luke:我在效仿 Freeman 和 Sanderson 的例子,但我将其更改为 public,但仍然遇到同样的异常。
-
@emragins,我将使用我的控制器中创建
newUser的代码来编辑我的帖子。 -
先试试这段代码,你用的是EF 4.1还是更高版本?我已经成功尝试过了,它正在工作blogs.msdn.com/b/adonet/archive/2011/03/15/…
标签: c# asp.net-mvc-3 ef-code-first