Entity framework 如何在DB first POCO模型中定义一个同时是PK和FK的字段

Entity framework 如何在DB first POCO模型中定义一个同时是PK和FK的字段,entity-framework,foreign-keys,entity-framework-6,Entity Framework,Foreign Keys,Entity Framework 6,表EMPLOYEE将MST\u SQ(主序列)作为主键,并作为表master主键的FK,该主键也称为MST\u SQ。此表也用于连接其他几个表,以便它们都具有相同的PK。我的理解是这样的 我需要在我的模型中定义classEmployee和classMaster之间的1:1关系,但我根本找不到这样做的方法。似乎只有具有多重性的关系才允许指定FK字段,而那些看起来像1到1的字段,例如具有可选(…)…WithRequiredPrincipal(…)的字段没有FK空间 加载时,我可以进行一些手动编码来链

EMPLOYEE
MST\u SQ
(主序列)作为主键,并作为表
master
主键的FK,该主键也称为
MST\u SQ
。此表也用于连接其他几个表,以便它们都具有相同的PK。我的理解是这样的

我需要在我的模型中定义class
Employee
和class
Master
之间的1:1关系,但我根本找不到这样做的方法。似乎只有具有多重性的关系才允许指定FK字段,而那些看起来像1到1的字段,例如具有可选(…)…WithRequiredPrincipal(…)的字段没有FK空间

加载时,我可以进行一些手动编码来链接
员工
主机
,但我如何知道它们已加载。是否有任何事件表明数据库正在填充POCO?或者,真正的问题是,如何在代码中定义这种关系

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

发件人:

因为属性的名称不符合约定 HasKey方法用于配置主键

员工拥有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
}
因此,您不需要“FK空格”,因为EF使其成为外键,而无需指定它

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