繁体   English   中英

ASP.NET MVC 3,代码优先EF:原始值?

[英]ASP.NET MVC 3, Code-First EF: OriginalValues?

我的代码似乎很简单:

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.

...那有什么意思? 我唯一能想到的是, newUseruserID为私有设置者,它的userIDnewUser 0,而userID作为主键应该由数据库生成。 但是,如果是问题所在,就不可能简单地使用Add()将对象插入到任何EF数据库中。 所以我很困惑。

在此先感谢任何可以帮助您对此有所了解的人。

预计newUser时间: 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表单传送到Controller。 userRep是我的用户存储库。

我认为这是由于您在保存newUser对象之前就在使用它。 尝试更改此行

bool addSuccess = userRep.Add(newUser);

bool addSuccess = userRep.Add(newUser, newRegistration.userName);

然后(鉴于passedUserName是上面的传递名称),将您的linq查询更改为:

var results = from user in Users
        where user.userName.Equals(passedUserName)
        select user;

祝好运!

可以确定的是,问题似乎源于对对象的“深层”引用或对引用的引用。 IOW,Foo类引用了Bar类,而Bar类引用了Baz类,后者引用了Foo类……显然,EF不太喜欢这种方式,因为它不容易验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM