简体   繁体   English

使用实体框架插入数据库时​​出错

[英]Error inserting into database using entity framework

I am going to get mad. 我要生气了。 I have a so simple code but it doesn't work. 我有一个非常简单的代码,但是没有用。

I have tested every thing and I can't understand the reason. 我已经测试了所有东西,但我不明白原因。

The code is like this: 代码是这样的:

FataDBEntities model = new FataDBEntities();

UserAccount nua = new UserAccount();

nua.username = username;
nua.pass = password;
nua.email = mailaddress;
nua.activated = false;

model.UserAccounts.Add(nua);

try
{
    model.SaveChanges();
}
catch (Exception)
{
    throw;
}

string activationCode;

try
{
    activationCode = genActivationCodeAndMail(mailaddress, username);
}
catch (Exception)
{
    throw;
}

ActivationCode ac = new ActivationCode();

ac.code = activationCode;
ac.expiration_date = DateTime.Now.AddDays(1);
nua = model.UserAccounts.Single(p => p.username == username);
ac.wichUser = nua.ID;

model.ActivationCodes.Add(ac);

try
{
    model.SaveChanges();
}
catch (Exception)
{
    throw;
}

and the model is like this : 和模型是这样的:

在此处输入图片说明

The error is with second insertion ... the first one works fine. 错误与第二次插入有关。。。第一次工作正常。

Additional information: Unable to update the EntitySet 'ActivationCode' because it has a DefiningQuery and no element exists in the element to support the current operation. 附加信息:无法更新EntitySet'ActivationCode',因为它具有DefiningQuery并且该元素中不存在任何元素来支持当前操作。

Please help... 请帮忙...

According to this SO article , this error can occur if the entity set is mapped from the database view, custom database query or if database table does not have primary key. 根据这篇SO文章 ,如果从数据库视图,自定义数据库查询映射实体集或数据库表没有主键,则可能发生此错误。

This has happened to me before, and I used that same article to fix the issue :) 这以前发生在我身上,我用同一篇文章来解决此问题:)

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

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