2

Hi I'm using the Code first method within Entity Framework using Visual Studio 2012 Could someone tell me if I should add context.SaveChanges(); at the end of my Seed method within the configuration.cs file in order to successfully update my tables? I can make structural changes using update-database -verbose in the console, but this doesn't update my data.

2 Answers 2

8

edit: you do in fact not need to call SaveChanges. Thus, this must mean that after the Seed method has been called, a call to SaveChanges is automatically made. However, it is perhaps useful to note that you can call SaveChanges() within the Seed method if you want, which can be useful when dealing with foreign key relations.

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

4 Comments

Hi thanks for your reply, I did though manage to populate my tables with initial data without using 'context.SaveChanges();', is this normal?
Apparently, I was mistaken. I am truly sorry. My answer has been modified.
Thanks, this makes sense because I could actually add data to everything but my foreign key ICollection property, is the 'SaveChanges' call a must for these types of updates?
Well, I'm not sure but I think so. I guess it depends on the objects stored in the foreign key collection. If you have objects in your foreign key collection that reference a class other than the class they are contained in, I think you need to ensure that the instances of that other class have been saved first. That way you can reference them from the objects in the foreign key collection. Does that make sense?
2

Initializers that provide Seed usually look like this inside...

// ...do something - prepare Db, Create etc.
Seed(context); // you override that
context.SaveChanges();

...just to clarify further.

Comments

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.