In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how Entity Framework manages one-to-one entity relationships. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
We now know how to use Code First to define simple domain classes and how to use DbContext classes to perform database operations. Now let's look at the diversity relationships in database theory, and we will use Code First to implement the following relationships:
1. One-to-one relationship: one to one
2. One-to-many relationship: one to many
3. Many-to-many relationship:: many to many
First of all, it is necessary to clarify the concept of relationship. A relationship is to define how two or more objects are associated. It is identified by the diversity values at both ends of the relationship, for example, one-to-many means that at one end of the relationship, there is only one entity, which we sometimes call a parent; at the other end of the relationship, there may be multiple entities, sometimes called children. EF API refers to those sides as principals and dependencies respectively. An one-to-many relationship is also called one or zero-to-many (One-or-Zero-to-Many), which means that a child may or may not have parents. There is also a slight change in the one-to-one relationship, where both ends of the relationship are optional.
I. entity relationship configuration in EF
Has method
With method
Configure entity relationships:
One-to-one table relationship design:
One-on-one relationships are not common, but they occur occasionally. If an entity has some optional data, then you can choose this design.
Configure one-to-one relationships using data annotations
In the example, the Person table is the master table and the IDCard table is the slave table.
1. Create a new entity class
The Person entity class structure is as follows:
Using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace configures one-to-one entity relationships. Model {/ main table / [Table ("Person")] public class Person {[Key] public int PersonId {get; set;} public string Name {get; set } public int Sex {get; set;} public int Age {get; set;} / virtual indicates that the navigation attribute is enabled for lazy loading / [ForeignKey ("PersonId")] public virtual IDCard IDCard {get; set;}
The IDCard entity class structure is as follows:
Using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;using System.Threading.Tasks;namespace configures one-to-one entity relations. Model {public class IDCard {[Key] public int PersonId {get; set;} public string IDCardNo {get; set;} public DateTime DataIssue {get; set;} public DateTime ValidTime {get; set;} public string IssuingAuthority {get; set } / Navigation Properties / public virtual Person Person {get; set;}} 2, create EF data context class using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;using configure one-to-one entity relationship .Model Namespace configures one-to-one entity relations. EF {public class EFDbContext: DbContext {public EFDbContext (): base ("name=CodeFirstApplication") {} public DbSet Persons {get; set;} public DbSet IDCards {get; set;}} 3. Create a database using data migration
An error was reported while using data migration: Unable to determine the principal end of an association between the types' configure one-to-one entity relationship. Model. Person 'and' configure one-to-one entity relationship. Model. ID Card'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations . By looking for information, the solution is as follows: add Required data annotations, and the modified Person class structure is as follows:
Using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace configures one-to-one entity relationships. Model {/ main table / [Table ("Person")] public class Person {[Key] public int PersonId {get; set;} public string Name {get; set } public int Sex {get; set;} public int Age {get; set;} / virtual indicates that the navigation attribute is enabled to load lazily / [ForeignKey ("PersonId")] [Required] public virtual IDCard IDCard {get; set;}} 4 to view the generated database table structure
By looking at the structure of the database table, it is found that the primary foreign key relationship is established between the Person table and the IDCards table.
Summary: to configure an one-to-one relationship using data annotations:
1. Use the data annotation Key to identify the primary key.
2. The primary key Key between two entities must be the same.
3. There are mutually referenced navigation attributes between the two entities (using virtual).
4. Set the foreign key relationship [ForeignKey ("PersonId")] in the main table.
3. Use FluentAPI to configure one-to-one relationship 1. Create the An entity class structure as follows: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace uses FluentAPI to implement .Model {public class A {get; set;} public string Name {get; set;} public virtual B B {get; set } 2. Create B entity class structure as follows: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace uses FluentAPI to implement .Model {public class B {get; set;} public string Name {get; set;} public virtual An A {get; set;}} 3, using FluentAPI to implement using System;using System.Collections.Generic Using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;using implements .Model using FluentAPI; namespace implements .EF {public class EFDbContext: DbContext {public EFDbContext (): base ("name=CodeFirstApplication") {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder.Entity (). ToTable ("IDCard") .HasKey (p = > p.PersonId) ModelBuilder.Entity () .ToTable ("Person") .HasKey (p = > p.PersonId); # region 1.0default one-to-one configuration / / modelBuilder.Entity () .HasRequired (p = > p.IDCard) .WithOptional () # endregion # region 2.0specifies who is the principal object and who is the dependent object / / specifies that the current Person object depends on the IDCard object, the foreign key will be created into the IDCard object, and the IDCard object is an independent table, which is misconfigured. / / modelBuilder.Entity () .HasRequired (p = > p.IDCard) .WithRequiredDependent (t = > t.Person); / / the correct dependency configuration is as follows: / / modelBuilder.Entity (). HasRequired (p = > p.Person). WithRequiredDependent (t = > t.IDCard); / / modelBuilder.Entity (). HasRequired (p = > p.B). WithRequiredDependent (d = > d.A) / / WithRequiredDependent A dependent object (A depends on Bscore B can exist in opposition, A will be established a foreign key) # endregion specifies who is the primary object modelBuilder.Entity (). HasRequired (p = > p.Person). WithRequiredPrincipal (t = > t.IDCard) / / WithRequiredPrincipal A principal object, execution An object is the decedent, that is, the parent, B inherits A Magi An independently exists / / modelBuilder.Entity (). HasRequired (p = > p.B). WithRequiredPrincipal (d = > d.A); # region MyRegion # endregion base.OnModelCreating (modelBuilder);}
The HasKey method is used to specify the primary key of a table, in other words, a unique value that allows us to find an entity. We didn't use this method before because we either used the Key feature or followed the default convention of EF (if the attribute name consists of a class name with a "Id" suffix or just "Id", then EF calculates the primary key). Because we now use PersonId as the primary key, we now need to provide additional hints to the runtime, which is where HasKey derivation is used. Finally, the primary key in the child table becomes the foreign key in the parent table.
Because this relationship is optional, it is also called one or zero-to-one (One-or-Zero-to-One). A relationship in which both ends of a relationship must exist is called one-to-one. For example, everyone must have a separate login, which is mandatory. You can also use WithRequiredDepentent or WithRequiredPrincipal methods instead of WithOptional methods.
Note: we can always configure the relationship from the principal side or the dependent side of the relationship. We always need to configure both sides of an one-to-one relationship (that is, two entities), using Has and With methods to ensure that an one-to-one relationship is created.
Thank you for reading! This is the end of the article on "how Entity Framework manages one-to-one entity relationships". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.