欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Entity?Framework管理一對一實(shí)體關(guān)系

 更新時(shí)間:2022年03月05日 09:35:12   作者:.NET開發(fā)菜鳥  
本文詳細(xì)講解了Entity?Framework管理一對一實(shí)體關(guān)系的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

我們現(xiàn)在已經(jīng)知道如何使用Code First來定義簡單的領(lǐng)域類,并且如何使用DbContext類來執(zhí)行數(shù)據(jù)庫操作。現(xiàn)在我們來看下數(shù)據(jù)庫理論中的多樣性關(guān)系,我們會使用Code First來實(shí)現(xiàn)下面的幾種關(guān)系:

  • 1、一對一關(guān)系: one to one
  • 2、一對多關(guān)系: one to many
  • 3、多對多關(guān)系::many to many

首先要明確關(guān)系的概念。關(guān)系就是定義兩個或多個對象之間是如何關(guān)聯(lián)的。它是由關(guān)系兩端的多樣性值識別的,比如,一對多意味著在關(guān)系的一端,只有一個實(shí)體,我們有時(shí)稱為父母;在關(guān)系的另一端,可能有多個實(shí)體,有時(shí)稱為孩子。EF API將那些端分別稱為主體和依賴。一對多關(guān)系也叫做一或零對多(One-or-Zero-to-Many),這意味著一個孩子可能有或可能沒有父母。一對一關(guān)系也稍微有些變化,就是關(guān)系的兩端都是可選的。

一、EF里的實(shí)體關(guān)系配置

Has方法

With方法

配置實(shí)體關(guān)系:

一對一表關(guān)系設(shè)計(jì):

一對一關(guān)系并不常用,但是偶爾也會出現(xiàn)。如果一個實(shí)體有一些可選的數(shù)據(jù),那么你可以選擇這種設(shè)計(jì)。

二、使用數(shù)據(jù)注解配置一對一關(guān)系

示例中Person表作為主表,IDCard表作為從表。

1、新建實(shí)體類

Person實(shí)體類結(jié)構(gòu)如下:

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 配置一對一實(shí)體關(guān)系.Model
{
    /// <summary>
    /// 主表
    /// </summary>
    [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; }

        /// <summary>
        /// virtual 表示是導(dǎo)航屬性 啟用貪懶加載
        /// </summary>
        [ForeignKey("PersonId")]
        public virtual IDCard IDCard { get; set; }
    }
}

IDCard實(shí)體類結(jié)構(gòu)如下:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 配置一對一實(shí)體關(guān)系.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; }

        /// <summary>
        /// 導(dǎo)航屬性
        /// </summary>
        public virtual Person Person { get; set; }
    }
}

2、創(chuàng)建EF數(shù)據(jù)上下文類

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 配置一對一實(shí)體關(guān)系.Model;

namespace 配置一對一實(shí)體關(guān)系.EF
{
    public class EFDbContext :DbContext
    {
        public EFDbContext()
            : base("name=CodeFirstApplication")
        {

        }

        public DbSet<Person> Persons { get; set; }

        public DbSet<IDCard> IDCards { get; set; }
    }
}

3、使用數(shù)據(jù)遷移的方式創(chuàng)建數(shù)據(jù)庫

在使用數(shù)據(jù)遷移的過程中報(bào)錯:Unable to determine the principal end of an association between the types '配置一對一實(shí)體關(guān)系.Model.Person' and '配置一對一實(shí)體關(guān)系.Model.IDCard'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations。通過查找資料,解決辦法如下:添加Required數(shù)據(jù)注解,修改后的Person類結(jié)構(gòu)如下:

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 配置一對一實(shí)體關(guān)系.Model
{
    /// <summary>
    /// 主表
    /// </summary>
    [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; }

        /// <summary>
        /// virtual 表示是導(dǎo)航屬性 啟用貪懶加載
        /// </summary>
        [ForeignKey("PersonId")]
        [Required]
        public virtual IDCard IDCard { get; set; }
    }
}

4、查看生成的數(shù)據(jù)庫表結(jié)構(gòu)

通過查看數(shù)據(jù)庫表結(jié)構(gòu),發(fā)現(xiàn)Person表和IDCards表建立了主外鍵關(guān)系。

總結(jié):使用數(shù)據(jù)注解配置一對一關(guān)系的步驟:

1、使用數(shù)據(jù)注解Key標(biāo)識主鍵。
2、兩個實(shí)體之間的主鍵Key必須相同。
3、兩個實(shí)體之間有相互引用的導(dǎo)航屬性(使用virtual)。
4、在主表中設(shè)置外鍵關(guān)系[ForeignKey("PersonId")]。

三、使用Fluent API來配置一對一關(guān)系

1、創(chuàng)建A實(shí)體類結(jié)構(gòu)如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 使用FluentAPI實(shí)現(xiàn).Model
{
    public class A
    {
        public int AId { get; set; }
        public string Name { get; set; }
        public virtual B B { get; set; }
    }
}

2、創(chuàng)建B實(shí)體類結(jié)構(gòu)如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 使用FluentAPI實(shí)現(xiàn).Model
{
    public class B
    {
        public int AId { get; set; }
        public string Name { get; set; }
        public virtual A A { get; set; }
    }
}

3、使用Fluent API實(shí)現(xiàn)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 使用FluentAPI實(shí)現(xiàn).Model;

namespace 使用FluentAPI實(shí)現(xiàn).EF
{
    public class EFDbContext :DbContext
    {
        public EFDbContext()
            : base("name=CodeFirstApplication")
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IDCard>().ToTable("IDCard").HasKey(p => p.PersonId);
            modelBuilder.Entity<Person>().ToTable("Person").HasKey(p => p.PersonId);


            #region 1.0 默認(rèn)一對一配置
            //modelBuilder.Entity<Person>().HasRequired(p => p.IDCard).WithOptional();

            #endregion

            #region 2.0 指定誰是主體對象誰是依賴對象
            // 指定當(dāng)前Person對象依賴IDCard對象,外鍵會創(chuàng)建到IDCard對象中,而IDCard對象是獨(dú)立存在的表,這種依賴關(guān)系配置是錯誤的。
            //modelBuilder.Entity<Person>().HasRequired(p => p.IDCard).WithRequiredDependent(t => t.Person);
            // 正確的依賴配置如下:
            //modelBuilder.Entity<IDCard>().HasRequired(p => p.Person).WithRequiredDependent(t => t.IDCard);
            //modelBuilder.Entity<A>().HasRequired(p => p.B).WithRequiredDependent(d=>d.A);//WithRequiredDependent A依賴對象(A依賴B,B可以對立存在,A會被建立外鍵)

            #endregion   指定誰是主要的對象
            modelBuilder.Entity<IDCard>().HasRequired(p => p.Person).WithRequiredPrincipal(t => t.IDCard);
            //WithRequiredPrincipal A 主體對象,執(zhí)行A對象為被繼承者,也就是父級,B繼承A,A獨(dú)立存在
            //modelBuilder.Entity<A>().HasRequired(p => p.B).WithRequiredPrincipal(d => d.A);
            #region MyRegion

            #endregion
            base.OnModelCreating(modelBuilder);
        }
    }
}

這里使用了HasKey方法,指定了一個表的主鍵,換言之,這是一個允許我們找到一個實(shí)體的獨(dú)一無二的值。之前我們沒有用這個方法是因?yàn)槲覀円从昧薑ey特性或者遵守了EF的默認(rèn)約定(如果屬性名是由類名加上"Id"后綴或者只是"Id"組成,那么EF會計(jì)算出該主鍵)。因?yàn)槲覀儸F(xiàn)在使用了PersonId作為主鍵,所以我們現(xiàn)在需要給運(yùn)行時(shí)提供額外的提示,這就是HasKey派生用場的地方。最后子表中的主鍵會成為父表中的外鍵。

因?yàn)樵撽P(guān)系是可選的,所以它也稱為一或零對一(One-or-Zero-to-One)。關(guān)系的兩端都是必須要存在的關(guān)系稱為一對一。比如,每個人必須要有一個單獨(dú)的login,這是強(qiáng)制性的。你也可以使用WithRequiredDepentent或者WithRequiredPrincipal方法來代替WithOptional方法。

注意:我們可以總是從該關(guān)系的主體端或者依賴端來配置關(guān)系。我們總是需要配置一對一關(guān)系的兩端(即兩個實(shí)體),使用Has和With方法確保一對一關(guān)系的創(chuàng)建。

到此這篇關(guān)于Entity Framework管理一對一實(shí)體關(guān)系的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論