ASP.NET MVC 3,代码优先 EF:原始值
本文关键字:EF 原始 代码 NET MVC ASP | 更新日期: 2023-09-27 18:32:50
我的代码似乎很简单:
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,即使它有一个私有 setter 并且 userID
作为主键,应该是数据库生成的。 但是,如果这是问题所在,则不可能简单地使用Add()
将对象插入任何 EF 数据库。 所以我很困惑。
提前感谢任何可以帮助阐明这一点的人。
ETA:newUser
由我的控制器中的以下代码创建:
[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,用于将数据从 Regiostration 窗体传送到控制器。 userRep
是我的用户存储库。
我认为这是因为您在保存之前正在使用 newUser 对象。尝试更改此行
bool addSuccess = userRep.Add(newUser);
自
bool addSuccess = userRep.Add(newUser, newRegistration.userName);
然后(给定传递的用户名是从上面传递的名称)将 linq 查询更改为:
var results = from user in Users
where user.userName.Equals(passedUserName)
select user;
祝你好运!
可以
确定的是,问题似乎源于对对象的"深层"引用,或对引用的引用。 IOW,类 Foo 引用了类 Bar,其中引用了类 Baz,其中引用了类 Foo...显然 EF 不太喜欢这样,因为它不容易验证。