The relationship between DB tables and the use of Fluent APIs in EF, effluent

Source: Internet
Author: User

The relationship between DB tables and the use of Fluent APIs in EF, effluent

Currently, most databases are relational databases, so the relationship between tables is particularly important. CRUD processing of data and subsequent data analysis are of great benefit. The following is an example of understanding the table relationship in the database and using the Fluent API in EF to create the relationship.

Associations between entities in the database

Quote in the book: In the real world, there is a link between the transaction and between the transactions. These connections are called the links between the entities and the entities in the computer, internal links are the links between entity attributes, and the links between entities can be divided into three types. (1:1, 1: n, n: n)

One-to-one)

In Entity A, each entity in entity B has at most one ing with it, and vice versa. This is A one-to-one relationship.

Eg: A class has only one class leader, while a class leader only works in one class. The class has one-to-one relationship with the shift leader.

Attribute Model

/// <Summary> /// Monitor indicates the class leader class /// </summary> public class Monitor {public Guid MonitorId {get; set;} public string MName {get; set;} public int MAge {get; set;} public virtual TheClass {get; set ;} // navigation property} // <summary> // TheClass indicates the class // </summary> public class TheClass {public TheClass () {this. students = new HashSet <Student> ();} public virtual Monitor {get; set;} // navigation attribute 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 ). witexceptional (x => x. monitor ). map (x => x. mapKey ("TheClassId"); // set 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 one-to-one implementation process, many problems occur, such as foreign key settings, and the relationship between the dependency class and the main class is unclear. these errors have always occurred at the beginning, leading to the inability to create models in the database, which is a waste of a long time. This is the problem we set in the Code. At this time, we can solve Baidu, blog Park, and so on, the above Fluent API code is correct.

2. One-to-multiple connections (1: n)

In Entity A, each entity corresponds to n (n> = 0) in entity B. In turn, each entity in entity B has only one corresponding object in Entity. This form is one-to-multiple connections.

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

Attribute

/// <Summary> /// TheClass indicates the class // </summary> public class TheClass {public TheClass () {this. students = new HashSet <Student> ();} public virtual Monitor {get; set;} // navigation attribute 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 {get; set;} // The student belongs to a class public virtual ICollection <Course> Courses {get; set ;}}

 

Fluent API (1: n)

    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);                       }    }    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

3. Multiple-to-multiple connections (n: n)

In Entity A, each entity in entity set B Corresponds to n entities (n> = 0). In turn, in entity B, each entity in entity set A corresponds to m objects. This relationship is multi-to-many Association.

Eg: Students and electives. (One student can take multiple courses, one course can be selected by multiple students), orders and products (one order contains multiple products, one product can be in multiple orders ).

Attribute 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 {get; set;} // The student belongs 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 (128); HasMany (x => x. students ). withiterator (x => x. courses ). map (m => {m. toTable ("CourseStudentId"); m. mapLeftKey ("CourseId"); m. mapRightKey ("StudentId") ;}); // set the table name and column name for the multi-to-Multi-link intermediate table }}

    public class StudentMap:EntityTypeConfiguration<Student>    {        public StudentMap()        {            ToTable("Student");            HasKey(x => x.SId);            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.Students);        }    }

Tables in the database

 

In the many-to-many relationship, we can set the table name and column name of the intermediate table, as shown above.

The above is the relationship between the three databases. One-to-one is a special case of one-to-many. one-to-many is a special case of many-to-many. We only have to master these basic knowledge, to understand the relationships in more complex tables.

Error

*: This error occurs when I use data migration. The reason is that the primary key I set is (SId, CId, TCId, MId ). EF reports an error when generating the database. We should set them to (StudentId, CourseId, TheClassId, MonitorId), so that our table will appear.

* The above error is largely due to the fact that I did not override the OnModelCreating class in EF. This is also the reason why I encountered many problems when creating multiple tables.

The code in the data context is as follows:

Public class BlogDbContent: DbContext, IDisposable {public BlogDbContent (): base ("name = BlogsEntities") {} 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 the configuration class /// </s Ummary> // <param name = "modelBuilder"> </param> protected override void OnModelCreating (DbModelBuilder modelBuilder) {var typesToRegister = Assembly. getExecutingAssembly (). 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. events. add (configurationInstance);} base. onModelCreating (modelBuilder );}}

Database connection string <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 the one-to-one relationship

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

Related Article

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.