Inheritance in Entity framework:table per Hierarchy

Source: Internet
Author: User
Tags connectionstrings

SOURCE Link

Introduction

This is the Entity Framework article series. In our previous-articles we learned various approaches to working with Entity Framework and various strategies To handle a database in a code first approach. You can read it here:

    • Code first approach in Entity Framework
    • Various database initialization Strategies in Entity Framework

In this article we'll learn to tackle inheritance in the Entity Framework. If you aren't clear on the aim of the article, the following should help explain it for you:

We know that inheritance are a beautiful concept in Object oriented programming and it provides the concept of Re-usabi Lity, which is one of the most important practices of software design principal. OK, so we'll implementinheritance at the class level, that's fine, but how would we implement it at the DB level? As a rule, we know the derive class contains all the properties of the base class, so would the derive class table cont Ain all the properties of the base class table?

We'll learn that stuff on this article along with next to the articles. There is three approaches in EntityFramework level to tackle inheritance at the code level.

    • Table per Hierarchy
    • Type per Hierarchy
    • Table per concrete Type

In this article we'll understand Table per Hierarchy. We know that inheritance are nothing but a hierarchical concept, where one class was derived from another class. It forms a tree structure by classes and subclasses. the table per hierarchy concept says that, one table would get create per hierarchy. For example, if there are Class A, and class B is the derived from Class A, then to that hierarchy only one table would get Created in the database. So the basic concept are for a and single hierarchy there'll be one table. There is a look at the below code.

Hide Shrink Copy Code
Using System;Using System.Collections.Generic;Using System.ComponentModel.DataAnnotations;Using System.Data.Entity;Using System.Linq;Using System.Text;Using System.Threading.Tasks;Using Newtonsoft.json;Namespace codefirst{PublicClass Person {[Key]Publicint PersonId {GetSet } [Required] [MaxLength (10)]PublicString Name {GetSet }PublicString Surname {GetSet } }public enum friendtype {Close, notclose, FamilyFriend} public class Friend:person {public Span class= "Code-sdkkeyword" >int32 person {get; set;} public friendtype friendtype {get; set;} } public class testcontext:dbcontext {public TestContext (): base (" dbconnectionstring") {} public dbset<person> person {get; set;} }} 

In this example, we had implemented one hierarchy by inheriting the  person  class within The&nbs P Friend  class. entity framework is smart enough to Implement table per Hierarchy without any external instructions.

Now let's has a look at the TestContext class. We is passing the connection string through the constructor and the connection string needs to being configured in the W Eb.config file. Within the class, we is initiating only Person the class and not the class Friend . This is the beauty of the Entity Framework. If we populate the base class then the related derive class would also automatically configure in a single table. The connection string in the Web.config file for this example.

Hide Copy Code
 <connectionstrings > <add name=" dbconnectionstring "connectionstring=" Data Source=SERVERNAME ; Initial catalog=persondb;integrated security=true "providername = "system.data.sqlclient" /< Span class= "Code-keyword" >> </connectionstrings>       

Once We run the application, we'll see that the database is created And table&nbs P;has generated as shown below.

If We closely look On table stricture we'll see one discriminator column. Why is the extra column created? We didn't implement it in the Code. entity  Framework has smartly created that field to distinguish Between tables. The concept is like this:both the  person  object and the  Friend  object Would save in a single table, so how we'll distinguish them? How would we know whether the particular row containing data is to the  person  object or the Fr Iend  object. To distinguish between them, the discriminator column has introduced. Here's the code where we are saving the object of  person  class: span>

Hide Copy Code
void Main (string[] args)        {            using (//table. ctx). Person.add ("Kayal"}); CTx. SaveChanges (); } }

There is a look on table data, we is seeing that ' person ' has saved in discriminator column value, so the record contains Object of the Person class.

Now, we'll save the object of the Friend class in the same table. A look at the below code:

Hide Copy Code
void Main (string[] args)        {            using (//table. ctx). Person.add ("1,friendtype =friendtype.close}"); CTx. SaveChanges (); } }

Here the data were saved in the table and the value for the discriminator column is Friend.

Customize the "discriminator" column

Could wonder:is it possible to change the default "discriminator" column name? Or change it ' s value? Yes, it ' s possible. Using The Fluent API we can do it. There is a look at the modified code.

Hide Copy Code
PublicClass Testcontext:dbcontext {Public TestContext ():Base "dbconnectionstring") {} public dbset<person> person {get; set;} protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {modelbuilder. Entity<person> (). map<friend> (M = m.requires (objecttype"). HasValue ( "friendtype")); Modelbuilder. Entity<person> (). map<person> (M = m.requires (objecttype"). HasValue ( "persontype"));}}      

Now, when we'll save the data of some Object. For example, the Friend Object would save the value "friend Type," unlike "friend" in the previous example. Let's try to save data using the code shown below.

Hide Copy Code
void Main (string[] args)        {            using (new TestContext ()) {ctx. Person.add ("1,friendtype =friendtype.close}"); CTx. SaveChanges (); } }

There is a look at the database structure. We are seeing this " FriendType " has saved on table because we have save object of Friend class.

Now, we'll try to save the object of Person class in a table. Here is sample code:

Hide Copy Code
void Main (string[] args) {            using (new TestContext ()) {ctx. Person.add ("Kumar"}); CTx. SaveChanges (); }}

Now, the value is ' person Type ' in table.

so we are learned the concept of table creation and the concept of the discriminator column, now we'll learn to FET CH data from the table. To fetch data from such a table, we can use both a polymorphic and a non-polymorphic query. Just try both of them:

Polymorphic–query

As the concept, it would pull all related hierarchical data in single query. Here we is pulling all data related to the Person Object. Now since Friend are derived from Person , Friend's information is pulling automatically. Here is the sample code.

Hide Copy Code
Using (new TestContext ())            {in                ctx. Person Select tab;                List<person> persons= data. ToList ();            } 

See that both Rowse has been fetched from the table so we are getting both the Friend and Person object.

Non-polymorphic Query

In this query we'll pull a particular column value. Here we is pulling the " Friend " "Object only.

Hide Copy Code
Using (new TestContext ())       {                //InCTX. person.oftype<friend> () Select tab; list<friend> persons = data. ToList (); }

And we is getting only a single object.

Border Line

We have learned to implement the Table per Hierarchy concept to implement inheritance in Entity Framework. Hopefully this article would help you to go ahead one step towards Entity Framework Learning. In the coming articles we'll understand the both additional inheritance strategies in the Entity Framework. E Nvironment.

License

This article, along with any associated source code and files, is licensed under the Code Project Open License (Cpol)

Inheritance in Entity framework:table per Hierarchy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.