[英]How to add data to SQL Server Express database using Entity Framework
I'm writing simple program for my university. 我正在为我的大学写简单的程序。 I created an Entity Framework model, draw diagrams, created database from model, applied SQL file on my database and now I'm trying to add some items to the DB.
我创建了一个实体框架模型,绘制图表,从模型创建数据库,在我的数据库上应用SQL文件,现在我正在尝试向数据库添加一些项目。
I'm doing it this way: 我是这样做的:
using (NewsletterEntities context = new NewsletterEntities())
{
Sender newSender = new Sender();
newSender.Login = Login.Text;
newSender.Password = Password.Text;
newSender.Port = 23;
newSender.SMTP = SMTP.Text;
newSender.Email = Email.Text;
newSender.SenderID = 0;
context.Senders.AddObject(newSender);
context.SaveChanges();
}
When I try to execute it it pops up with inner exception: 当我尝试执行它时会弹出内部异常:
Cannot insert explicit value for identity column in table 'Senders' when IDENTITY_INSERT is set to OFF.
当IDENTITY_INSERT设置为OFF时,无法在表'Senders'中为identity列插入显式值。
I was trying to look for the error, but I don't know much about entity framework and couldn't find anything specific. 我试图寻找错误,但我不太了解实体框架,也找不到具体的东西。
Can anyone help? 有人可以帮忙吗?
The error is not about Entity Framework, it's about SQL Server, more specifically the Identity column . 该错误与Entity Framework无关,它与SQL Server有关,更具体地说是Identity列 。
My guess is that SenderID
is an identity column. 我的猜测是
SenderID
是一个标识列。 This means that the database is responsible for assigning sequential values to this field and you are not allowed to specify values for it (except if you use IDENTITY_INSERT
, as the error message suggests). 这意味着数据库负责为此字段分配顺序值,并且不允许为其指定值(除非您使用
IDENTITY_INSERT
,否则会显示错误消息)。
Therefore, dropping the newSender.SenderID = 0;
因此,删除
newSender.SenderID = 0;
line from your code should solve the issue. 代码中的行应解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.