如何在DB中定义第一个POCO模型,即PK和FK的字段

时间:2013-11-18 13:28:51

标签: entity-framework foreign-keys entity-framework-6

EMPLOYEE具有MST_SQ(主序列)作为它的主键,并且作为表MASTER的主键的FK,也称为MST_SQ }。此表用于连接其他几个表,以便它们都具有相同的PK。这就是我的理解。

我需要在我的模型中定义类Employee和类Master之间的1对1关系,但我找不到这样做的方法。似乎只有与multiplicty的关系允许FK字段被设定,而那些看起来像1到1的字段,例如具有可选(...).. WithRequiredPrincipal(....)没有FK空间。

我可以进行一些手动编码,以便在加载时链接EMPLOYEEMASTER,但我怎么能告诉他们已加载。是否有任何事件表明POCO是从DB填充的?或者,真正的问题是,我如何在代码中定义这种关系?

1 个答案:

答案 0 :(得分:1)

来自Relationships and Navigation Properties

  

当使用1对1或1对0..1关系时,没有   单独的外键列,主键属性充当   外键

来自Configuring a Required-to-Optional Relationship (One-to–Zero-or-One)

  

因为该属性的名称不符合惯例   HasKey方法用于配置主键

public class Master
{
    public int MST_SQ { get; set; }

    public virtual Employee Employee { get; set; }
}

public class Employee
{
    public int MST_SQ { get; set; }

    public virtual Master Master { get; set; }
}

Employee具有MST_SQ属性,该属性是主键和外键:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Master>().HasKey(m => m.MST_SQ);

    modelBuilder.Entity<Employee>().HasKey(e => e.MST_SQ);

    modelBuilder.Entity<Employee>()
                .HasRequired(e => e.Master) //Employee is the Dependent and gets the FK
                .WithOptional(m => m.Employee); //Master is the Principal
}

生成的迁移代码:

        CreateTable(
            "dbo.Employees",
            c => new
                {
                    MST_SQ = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.MST_SQ)
            .ForeignKey("dbo.Masters", t => t.MST_SQ)
            .Index(t => t.MST_SQ);

        CreateTable(
            "dbo.Masters",
            c => new
                {
                    MST_SQ = c.Int(nullable: false, identity: true),
                })
            .PrimaryKey(t => t.MST_SQ);

因此您不需要“FK空间”,因为EF使其成为外键而无需您指定它