3

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I already did that and it didn't work. In sql manager I turned on identity specification cause as far as i know it allows to increment id automaticly.
@saajuu: You also need to make sure the SenderID is properly defined in the model - it has to have StoreGenerationPattern set to Identity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.