Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Entity Framework to initialise collections on my newly-created entities?

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?

like image 943
Danny Tuppeny Avatar asked May 12 '11 17:05

Danny Tuppeny


People also ask

How do I update my Entity Framework database first?

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.

How do I use database first approach in Entity Framework?

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.

How do I code first in Entity Framework?

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…


1 Answers

With POCO entities and EF, I generally initialize collection in the constructor. And, I prefer ISet over ICollection ;-)

like image 170
Fabian Vilers Avatar answered Oct 06 '22 14:10

Fabian Vilers