I'm trying to seed my database with some test data with an IDatabaseIntialiser
like this:
protected override void Seed(BlogDataContext context)
{
// <snip>
var post = context.Posts.Create();
post.Title = "My Life On Twitter";
// <snip properties>
// Set tags
post.Tags.Add(aspnetTag); // NullRefException
post.Tags.Add(razorTag);
Post entity looks like this:
public class Post
{
// ...
public virtual ICollection<Tag> Tags { get; set; }
Full entities at Bitbucket: Post and Tag. All code is at http://code.dantup.com/blog
However, post.Tags
is null, so this doesn't work. Originally I was creating post as new Post()
, however since I'm calling the Create
method provided by the EF, why is the collection not initialised?
It feels clumsy to instantiate my own collection here, and if I do it in the constructor, presumably every time I load an entity from EF, it'll create the collection in the constructor and then overwrite it with one containing the actual data from the DB?
Is there some way to tell EF to create me an entity, including collections/proxies for my ICollections
(assuming ICollection
is the right choice)?
Edit: context.Configuration.ProxyCreationEnabled
is set to true (by default), which seems to exist for this reason?
Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.
Step 1 − Let's create a new console project with DatabaseFirstDemo name. Step 2 − To create the model, first right-click on your console project in solution explorer and select Add → New Items… Step 3 − Select ADO.NET Entity Data Model from middle pane and enter name DatabaseFirstModel in the Name field.
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
With POCO entities and EF, I generally initialize collection in the constructor. And, I prefer ISet over ICollection ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With