简体   繁体   中英

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.

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.

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 .

My guess is that SenderID is an identity column. 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).

Therefore, dropping the newSender.SenderID = 0; line from your code should solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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