Sander Van Looverenhttps://blog.sandervanlooveren.be/
The story of a .NET developerArticulate, blogging built on Umbraco1071https://blog.sandervanlooveren.be/posts/inheritance-with-entity-framework/
Entity FrameworkInheritanceInheritance with Entity Framework<p>When we are using Enitity Framework code first to define our model, chances are that we will probably want to use some inheritance here and there. Using migrations to create our database, there are different ways to define this inheritance in our database. I will show you the most commonly used ways of generating tables based on inherited classes.</p>
<h3>Setup</h3>
<p>For this post we'll get the help of our favorite pets, a cat and a dog, which both happen to be animals. Great, we'll go with <strong>Kitty the cat</strong> and <strong>Buddy the dog</strong>!</p>
<p>Lets first define our Animal. Well first of all we are using Entity Framework to save them in the database so they should both have an Id. The most common thing our pets have in common is that they both have a name. So we'll add that as a property of our animal.</p>
<p>Now lets talk about Kitty, our cat. We all know cats have 9 lives and dogs don't. So lets create a property to determine how many lives our cat has got left (LivesLeft).</p>
<p>To make Buddy feel unique lets give the dog a unique property. Hmm... what do dogs have or do, that cats don't? ... Of course! They guard our homes! Lets keep track of how many times Buddy has successfully defended our home (HomesDefended).</p>
<pre class="cs"><span>public abstract</span> <span>class</span> <span>Animal</span>
{
<span>public</span> <span>int</span> Id { <span>get</span>; <span>set</span>; }
<span>public</span> <span>string</span> Name { <span>get</span>; <span>set</span>; }
}
<span>public</span> <span>class</span> <span>Cat</span> : <span>Animal</span>
{
<span>public</span> <span>int</span> LivesLeft { <span>get</span>; <span>set</span>; }
}
<span>public</span> <span>class</span> <span>Dog</span> : <span>Animal</span>
{
<span>public</span> <span>int</span> HomesDefended { <span>get</span>; <span>set</span>; }
}</pre>
<p>These are the classes I made for the setup I just explained. I have made Animal abstract because we never want to create an instance of Animal, it will always be a cat or a dog.</p>
<p>Now we got our model, but there are different ways to save our animals to the database. I'll explain the 3 most common ways you would want to do this.</p>
<h3>1. A single table</h3>
<p>The simplest way is probably to have just 1 table in our database which will hold all our animals. This is probably not what you are looking for but nevertheless I'll show you how to do this.</p>
<h4>The context</h4>
<p>In our context we have only 1 DbSet which holds our Animals (no cats, no dogs, they are all just animals).</p>
<pre class="cs"><span>public</span> <span>class</span> <span>ApplicationDbContext1</span> : <span>DbContext</span>
{
<span>public</span> <span>DbSet</span>&lt;<span>Animal</span>&gt; Animals { <span>get</span>; <span>set</span>; }
<span>public</span> ApplicationDbContext1() : <span>base</span>(<span>"Inhertiance1"</span>) { }
}</pre>
<h4>Seed</h4>
<p>To have actual data in our database I have implemented the Seed method for our context. Because it only has a list of Animals, we'll have to add Kitty and Buddy straight to our animals collection as shown in the code below.</p>
<pre><span>protected</span> <span>override</span> <span>void</span> Seed(<span>ApplicationDbContext1</span> context)
{
context.Animals.AddRange(<span>new</span> <span>List</span>&lt;<span>Animal</span>&gt;
{
<span>new</span> <span>Cat</span>
{
Name = <span>"Kitty"</span>,
LivesLeft = 9
},
<span>new</span> <span>Dog</span>
{
Name = <span>"Buddy"</span>,
HomesDefended = 0
}
});
}</pre>
<h4>The migration</h4>
<p>I have added the migration created by EF just for reference. We'll have a look at the database using the data &amp; diagram below.</p>
<pre class="cs"><span>public</span> <span>partial</span> <span>class</span> <span>CreateDB1</span> : <span>DbMigration</span>
{
<span>public</span> <span>override</span> <span>void</span> Up()
{
CreateTable(
<span>"dbo.Animals"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>, identity: <span>true</span>),
Name = c.String(),
LivesLeft = c.Int(),
HomesDefended = c.Int(),
Discriminator = c.String(nullable: <span>false</span>, maxLength: 128),
})
.PrimaryKey(t =&gt; t.Id);
}
<span>public</span> <span>override</span> <span>void</span> Down()
{
DropTable(<span>"dbo.Animals"</span>);
}
}</pre>
<h4>The database</h4>
<p> <img style="width: 192px; height: 183px; float: left;" src="https://blog.sandervanlooveren.be/media/1011/1-database-diagram.png?width=192&amp;height=183" alt="Database diagram" data-id="1082"><img style="width: 348px; height: 94px; float: left;" src="https://blog.sandervanlooveren.be/media/1012/1-table-data.png?width=348&amp;height=94" alt="Database data" data-id="1083"></p>
<p> </p>
<p style="clear: both;">As expected we have only created one table for our Animals in the database. This means that all records have all the properties of Animal (Id &amp; Name), the property of our Cat (LivesLeft) and the property of our Dog (HomesDefended). In addition EF has created an extra column (Discriminator) to determine which record is which animal. As you can see in the sample data, the first one is Kitty the cat and the second one is Buddy the dog. You also notice that the record for Kitty has a NULL value in HomesDefended because it is not a cat property, and the same is true for Buddy's record. I personally don't like having these NULL values in my DB and of course we all know putting cats and dogs together is usually a bad idea! To fix this, lets have a look at the second approach.</p>
<h3>2. A table for everyone</h3>
<p>If we want to normalize our database and keep different things in different tables, this approach will work better. Here we will create a table for each of our classes. A table for Animals, which will hold the common properties, A table for Cats and a table for Dogs which will be linked to our Animal table.</p>
<h4>The context</h4>
<p>For the reasons stated above I have created 3 DbSets 1 for Animals, 1 for Cats and 1 for Dogs. If this would be the only changes made, we would still end up with the same table as in the 1st example. To have our Cats and Dogs tables created I have overridden the method OnModelCreating. In this method I have specified that Kitty and Buddy both want there own separate tables.</p>
<pre><span>public</span> <span>class</span> <span>ApplicationDbContext2</span> : <span>DbContext</span>
{
<span>public</span> <span>DbSet</span>&lt;<span>Animal</span>&gt; Animals { <span>get</span>; <span>set</span>; }
<span>public</span> <span>DbSet</span>&lt;<span>Cat</span>&gt; Cats { <span>get</span>; <span>set</span>; }
<span>public</span> <span>DbSet</span>&lt;<span>Dog</span>&gt; Dogs { <span>get</span>; <span>set</span>; }
<span>public</span> ApplicationDbContext2() : <span>base</span>(<span>"Inhertiance2"</span>) { }
<span>protected</span> <span>override</span> <span>void</span> OnModelCreating(<span>DbModelBuilder</span> modelBuilder)
{
modelBuilder.Entity&lt;<span>Cat</span>&gt;().ToTable(<span>"Cats"</span>);
modelBuilder.Entity&lt;<span>Dog</span>&gt;().ToTable(<span>"Dogs"</span>);
<span>base</span>.OnModelCreating(modelBuilder);
}
}</pre>
<h4>Seed</h4>
<p>Because we now have 3 properties on our context we have multiple ways to add Kitty and Buddy to the database. Since we still have our Animals property we could just keep the seed exactly the same as in the first example. But because we have seperate properties for cats and dogs I'dd rather use those.</p>
<pre><span>protected</span> <span>override</span> <span>void</span> Seed(<span>ApplicationDbContext2</span> context)
{
<span>//context.Animals.AddRange(new List&lt;Animal&gt;</span>
<span>//{</span>
<span>// new Cat</span>
<span>// {</span>
<span>// Name = "Kitty",</span>
<span>// LivesLeft = 9</span>
<span>// },</span>
<span>// new Dog</span>
<span>// {</span>
<span>// Name = "Buddy",</span>
<span>// HomesDefended = 0</span>
<span>// }</span>
<span>//});</span>
<span>//Or this</span>
context.Cats.Add(<span>new</span> <span>Cat</span>
{
Name = <span>"Kitty"</span>,
LivesLeft = 9
});
context.Dogs.Add(<span>new</span> <span>Dog</span>
{
Name = <span>"Buddy"</span>,
HomesDefended = 0
});
}</pre>
<h4>The migration</h4>
<p>Again, for reference.</p>
<pre><span>public</span> <span>partial</span> <span>class</span> <span>CreateDB2</span> : <span>DbMigration</span>
{
<span>public</span> <span>override</span> <span>void</span> Up()
{
CreateTable(
<span>"dbo.Animals"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>, identity: <span>true</span>),
Name = c.String(),
})
.PrimaryKey(t =&gt; t.Id);
CreateTable(
<span>"dbo.Cats"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>),
LivesLeft = c.Int(nullable: <span>false</span>),
})
.PrimaryKey(t =&gt; t.Id)
.ForeignKey(<span>"dbo.Animals"</span>, t =&gt; t.Id)
.Index(t =&gt; t.Id);
CreateTable(
<span>"dbo.Dogs"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>),
HomesDefended = c.Int(nullable: <span>false</span>),
})
.PrimaryKey(t =&gt; t.Id)
.ForeignKey(<span>"dbo.Animals"</span>, t =&gt; t.Id)
.Index(t =&gt; t.Id);
}
<span>public</span> <span>override</span> <span>void</span> Down()
{
DropForeignKey(<span>"dbo.Dogs"</span>, <span>"Id"</span>, <span>"dbo.Animals"</span>);
DropForeignKey(<span>"dbo.Cats"</span>, <span>"Id"</span>, <span>"dbo.Animals"</span>);
DropIndex(<span>"dbo.Dogs"</span>, <span>new</span>[] { <span>"Id"</span> });
DropIndex(<span>"dbo.Cats"</span>, <span>new</span>[] { <span>"Id"</span> });
DropTable(<span>"dbo.Dogs"</span>);
DropTable(<span>"dbo.Cats"</span>);
DropTable(<span>"dbo.Animals"</span>);
}
}</pre>
<h4>The database</h4>
<p> <img style="width: 396px; height: 296px; float: left;" src="https://blog.sandervanlooveren.be/media/1013/2-database-diagram.png?width=396&amp;height=296" alt="Database diagram" data-id="1084"><img style="width: 165px; height: 238px; float: left;" src="https://blog.sandervanlooveren.be/media/1014/2-table-data.png?width=165&amp;height=238" alt="Table data" data-id="1085"></p>
<p style="clear: both;">EF has created 3 tables in our database, one that holds the basic properties of our animals, and 2 other that hold the specifics for each animal. Our Cats and Dogs tables both have a foreign key to our Animals table so if we want to query them to read all there properties we will have to join with our Animals table. This way our database is normalized and we don't have any unnecessary NULL values which is great! But on the other hand this adds some complexity to our database when querying it manually. That's why we"ll take a look at yet an other approach we can take.</p>
<h3>3. Only tables for subclasses</h3>
<p>This time we just want a table that holds our cats and a table that holds our dogs. This means that we won't have a table for our animals, so the Id and Name properties will have to become columns of our Cats and Dogs tables.</p>
<h4>The context</h4>
<p>Doing this is easy, all we have to do is create 2 DbSets, 1 for our Cats and 1 for our Dogs.</p>
<pre><span>public</span> <span>class</span> <span>ApplicationDbContext3</span> : <span>DbContext</span>
{
<span>public</span> <span>DbSet</span>&lt;<span>Cat</span>&gt; Cats { <span>get</span>; <span>set</span>; }
<span>public</span> <span>DbSet</span>&lt;<span>Dog</span>&gt; Dogs { <span>get</span>; <span>set</span>; }
<span>public</span> ApplicationDbContext3() : <span>base</span>(<span>"Inhertiance3"</span>) { }
}</pre>
<h4>Seed</h4>
<p>We can reuse the same seed as we used in our 2nd approach, Kitty goes in the Cats DbSet and Buddy is added to our Dogs.</p>
<pre><span>protected</span> <span>override</span> <span>void</span> Seed(<span>ApplicationDbContext3</span> context)
{
context.Cats.Add(<span>new</span> <span>Cat</span>
{
Name = <span>"Kitty"</span>,
LivesLeft = 9
});
context.Dogs.Add(<span>new</span> <span>Dog</span>
{
Name = <span>"Buddy"</span>,
HomesDefended = 0
});
}</pre>
<h4>The migration</h4>
<p>You know why I put this here. :)</p>
<pre><span>public</span> <span>partial</span> <span>class</span> <span>CreateDB3</span> : <span>DbMigration</span>
{
<span>public</span> <span>override</span> <span>void</span> Up()
{
CreateTable(
<span>"dbo.Cats"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>, identity: <span>true</span>),
LivesLeft = c.Int(nullable: <span>false</span>),
Name = c.String(),
})
.PrimaryKey(t =&gt; t.Id);
CreateTable(
<span>"dbo.Dogs"</span>,
c =&gt; <span>new</span>
{
Id = c.Int(nullable: <span>false</span>, identity: <span>true</span>),
HomesDefended = c.Int(nullable: <span>false</span>),
Name = c.String(),
})
.PrimaryKey(t =&gt; t.Id);
}
<span>public</span> <span>override</span> <span>void</span> Down()
{
DropTable(<span>"dbo.Dogs"</span>);
DropTable(<span>"dbo.Cats"</span>);
}
}</pre>
<h4>The database</h4>
<p> <img style="width: 173px; height: 274px; float: left;" src="https://blog.sandervanlooveren.be/media/1015/3-database-diagram.png?width=173&amp;height=274" alt="Database diagram" data-id="1086"><img style="width: 212px; height: 133px; float: left;" src="https://blog.sandervanlooveren.be/media/1016/3-table-data.png?width=212&amp;height=133" alt="Table data" data-id="1087"></p>
<p style="clear: both;">The tables created here are nice and simple, no relations, no NULL values. You can see that each table has the properties which were defined in our Animal class and the animal specific properties are only in there responsive tables.</p>
<h3>Conclusion</h3>
<p>I have given you 3 common ways to create different database layouts using the same model. When it comes to choosing the right one for your needs, you will have to analyse what you want to achieve.</p>
<p>If you like simplicity and don't care about NULL values in your database, you could choose the first approach. If you are concerned about database normalization and have complex inheritance with lots of properties, you should probably go for the 2nd approach. If your don't have lots of inheritance and you want to have separate tables for your entities I think you should go for the 3rd approach. But of course it all depends on what you prefer.</p>
<p>For this setup I would definitely go for the 3rd approach. There is only 1 property which our animals have in common so that's why I find it a bit overkill to have 3 separate tables. And I wouldn't put them all in one table because I don't like having NULL values in my database. Apart from that, I think its better to keep cats and dogs as far away from each other as possible, we all know how Kitty and Buddy can be. ;)</p>
<p>Thanks for reading, and if you have any suggestions, question or you want to share something else, please comment below!</p>Wed, 15 Mar 2017 08:00:00 +01002017-03-15T08:00:00+01:00