The relationship between DB tables and the use of the fluent API in EF

Source: Internet
Author: User
Tags connectionstrings

Now that the majority of the database is a relational database, the relationship between the table and the table is particularly important, for the data crud processing and future data analysis has great benefits. The following is an example of the understanding of table relationships in a database and the use of the fluent API in EF to create such relationships.

Connections between entities in the database

In the real world, there is a connection between the inside of the transaction and the transaction, which is called the connection between the entities and the internal relations within the computer, and the internal connection is the connection between the entity attributes, and the relations between the entities can be divided into three categories. (1:1, 1:n, n ' an)

A: one-off contact (1:1)

Each entity in a entity set has at most one entity associated with it in entity set B, and vice versa.

Eg: there is only one squad leader in a class, and a monitor only serves in one class. Class and Monitor is a one-to-one relationship.

  property model

<summary>//Monitor represents class monitor///</summary> public class Monitor {public Guid Monitorid        {get; set;}        public string Mname {get; set;}        public int MAge {get; set;}                        Public virtual Theclass Theclass {get; set;}  Navigation Properties}///<summary>//Theclass indicates class///</summary> public class Theclass {public Theclass () {this.        Students = new hashset<student> ();                          } public virtual monitor monitor {get; set;}        Navigation Property Public Guid Theclassid {get; set;}        public string Tcname {get; set;}        public int Tcnumber {get; set;}            Public virtual icollection<student> Students {get; set;} There are many students in the class}

Fluent API (1:1)

public class Monitormap:entitytypeconfiguration<monitor> {public Monitormap ()} {this.            ToTable ("Monitor"); This.                        Haskey (X=>x.monitorid); Property (x = X.mname).            Hasmaxlength (128);            Property (x = X.mage); This. hasrequired (x = x.theclass). Withoptional (x = x.monitor).    Map (x = X.mapkey ("Theclassid"));                    This sets the monitor as a dependent class and theclassid as a foreign key.            }} public class Theclassmap:entitytypeconfiguration<theclass> {public Theclassmap () {            ToTable ("Theclass");            Haskey (x = x.theclassid); Property (x = X.tcname).            Hasmaxlength (128);            Property (x = X.tcnumber);                          Hasmany (x = x.students);                       Hasoptional (x = x.monitor); }    }

Tables in the database

In the implementation of a one-to the process, there are a lot of problems, that is, the problem of foreign key settings, dependent classes and the main class relationship is unclear. These are just the beginning of the error, resulting in the database model can not be created, wasted a long time, this situation is our code inside the problem of setting, at this time we Baidu, blog It is correct in the fluent API code above.

Two: one-to-many links (1:n)

Each entity in a entity set has n entities in the B entity set (n>=0), in turn, each entity in the B entity set has only 1 corresponding to it. This form is a one-to-many connection.

Eg: the relationship between the class set and the students in the class set. The relationship between the school and the students.

Property

///<summary>//Theclass indicates class///</summary> public class Theclass {public Theclass ( ) {this.        Students = new hashset<student> ();                                  } public virtual monitor monitor {get; set;}        Navigation Property Public Guid Theclassid {get; set;}        public string Tcname {get; set;}        public int Tcnumber {get; set;}            Public virtual icollection<student> Students {get; set;} There are many students in the class} 
    <summary>    ///Student table///</summary> public class Student {public        Student ()        { This            . Courses=new collection<course> ();        }        Public Guid StudentID {get; set;}          public string SName {get; set;}          public int SAge {get; set;}          Public Guid Theclassid {get; set;}          Public virtual  Theclass Theclass {get; set;}          Students belong to a class public        virtual icollection<course> Courses {get; set;}    }

Fluent API (1:N)

public class Theclassmap:entitytypeconfiguration<theclass> {public Theclassmap () {Tota            BLE ("Theclass");            Haskey (x = x.theclassid); Property (x = X.tcname).            Hasmaxlength (128);            Property (x = X.tcnumber);                          Hasmany (x = x.students);                       Hasoptional (x = x.monitor);            }} public class Studentmap:entitytypeconfiguration<student> {public Studentmap () {            ToTable ("Student");            Haskey (x = X.studentid); Property (x = X.sname).            Hasmaxlength (128); hasrequired (x = x.theclass). Withmany (x = x.students).            Hasforeignkey (x = x.theclassid); Hasmany (x = x.courses).        Withmany (x = x.student); }    }

Tables in the database

Three: Many-to-many links

Each entity in a entity set has n entities corresponding to it in entity set B (n>=0), and in turn, each entity in the B entity set has an M entity in entity sets a corresponding to it, which is a many-to-many relationship.

eg: students and elective courses. (One student can take multiple courses, one course can be elective by multiple students), orders and products (one order has multiple products, one product can be in multiple orders).

Property model

///<summary>///Course class///</summary> public class Course {public Course () { This.        Student=new collection<student> ();        } public Guid CourseID {get; set;}        public string CName {get; set;}    Public virtual icollection<student> Student {get; set;} }
    <summary>    ///Student table///</summary> public class Student {public        Student ()        { This            . Courses=new collection<course> ();        }          Public Guid StudentID {get; set;}          public string SName {get; set;}          public int SAge {get; set;}          Public Guid Theclassid {get; set;}          Public virtual  Theclass Theclass {get; set;}          Students belong to a class public           virtual icollection<course> Courses {get; set;}    }

Fluent API

    public class coursemap:entitytypeconfiguration<course>    {public        coursemap ()        {            ToTable (" Course ");            Haskey (x = x.cid);            Property (x = X.cname). Hasmaxlength (+);            Hasmany (x = x.students). Withmany (x=>x.courses). Map (M + =            {                m.totable ("Coursestudentid");                M.mapleftkey ("CourseID");                M.maprightkey ("StudentID");            });                                                     This sets the table name and column name of the many-to-many relationship intermediate table        }    }

    public class studentmap:entitytypeconfiguration<student>    {public        studentmap ()        {            ToTable (" Student ");            Haskey (x = x.sid);            Property (x = X.sname). Hasmaxlength (+);            hasrequired (x = x.theclass). Withmany (x=>x.students). Hasforeignkey (X=>X.THECLASSID);            Hasmany (x = x.courses). Withmany (x=>x.students);        }    }

Tables in the database

In a many-to-many relationship, we can set the table name and column name of the intermediate table, just like the above.

The above is the database table of the three-way relationship, wherein the pair of one is a pair of more special cases, a pair of more than many of the special case, we can only grasp the most basic knowledge, in order to understand the more complex relationships in the table.

Error occurred

*: This is the error I have when using data migration. The reason is that my previous primary key is set (Sid,cid,tcid,mid). EF makes the error when generating the database, we should set them to (Studentid,courseid,theclassid,monitorid), this will appear our table.

* The above error is largely due to the fact that I did not rewrite the Onmodelcreating class in EF, and the problem with many of my previous creation of multiple tables was caused by this.

below is a code in the data context

    public class Blogdbcontent:dbcontext, IDisposable {public blogdbcontent (): Base ("Name=blogsen        Tities ") {} public dbset<bloguser> Bloguser {get; set;}        Public dbset<post> Post {get; set;}        Public dbset<course> Course {get; set;}        Public dbset<student> Students {get; set;}        Public dbset<theclass> Theclass {get; set;}        Public dbset<monitor> Monitor {get; set;} <summary>///Rewrite configuration class///</summary>//<param name= "ModelBuilder" ></param&gt        ; protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {var typestoregister = assembly.ge Texecutingassembly (). GetTypes (). Where (type =!) String.IsNullOrEmpty (type. Namespace)). Where (Type = = Type. BaseType! = null && type. Basetype.isgenerictype && type. Basetype.getgenerictypedefinition () = = typeof (Entitytypeconfiguration<>)); foreach (var type in typestoregister) {Dynamic configurationinstance = Activator.CreateInstance                (type);            MODELBUILDER.CONFIGURATIONS.ADD (configurationinstance); } base.        Onmodelcreating (ModelBuilder); }    }

Connection string for database <App.Config>

  <connectionStrings>    <add name= "blogsentities" connectionstring= "Data source=localhost;initial Catalog =ahui_blog;integrated Security=false;         Persist Security Info=false; User Id=sa; password=****** "providername=" System.Data.SqlClient "/>  </connectionStrings>

Attachment:

Fluent API Reference

Http://www.cnblogs.com/oppoic/p/ef_one-to-one_one-to-many_many-to-many_cascadedelete.html

Http://www.cnblogs.com/panchunting/p/entity-framework-code-first-fluent-api-configuring-relationships.html

Understanding one-to-one relationships

Http://www.cnblogs.com/dudu/archive/2011/07/08/entity_framework_one_to_one_two_way.html

The relationship between DB tables and the use of the fluent API in EF

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.