如何创建实体框架中使用两个外键5码第一个主键? [英] How do I create a primary key using two foreign keys in Entity Framework 5 code first?
问题描述
我所在的主键由两个外键另外两个表的实体。我有以下,但有两个FK引用生成的表的配置工作。
I have an entity where the primary key consists of two foreign keys to two other tables. I have the configuration working with the following but the table is generated with two FK references.
表:
domain.Entity1
MorePK (PK, FK, int, not null)
Entity2_Id (PK, FK, int, not null)
Entity3_Id (PK, FK, int, not null)
OtherData (varchar, null)
Entity2_Id1 (FK, int, null)
Entity3_Id1 (FK, int, null)
is generated from:
从产生ENTITY1
{
公众诠释MorePK {搞定;组; }
公众诠释Entity2_Id {搞定;组; }
公众诠释Entity3_Id {搞定;组; }
公共字符串OtherData {搞定;组; }
公共虚拟ENTITY2 ENTITY2 {搞定;组; }
公共虚拟ENTITY3 ENTITY3 {搞定;组; }
}
公共ENTITY2
{
公众诠释标识{搞定;组; }
公共虚拟目录<&ENTITY1 GT; Entity1s {搞定;组; }
}
公共ENTITY3
{
公众诠释标识{搞定;组; }
公共虚拟目录<&ENTITY1 GT; Entity1s {搞定;组; }
}
公共类Entity1Config:EntityTypeConfiguration<&ENTITY1 GT;
{
HasKey(K =>新建{k.MorePK,k.Entity2_Id,k.Entity3_Id});
HasRequired(P => p.Entity2)
.WithMany()
.HasForeignKey(P => p.Entity2_Id);
HasRequired(P => p.Entity3)
.WithMany()
.HasForeignKey(P => p.Entity3_Id);
房产(X => x.Entity2_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
房产(X => x.Entity3_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
public Entity1
{
public int MorePK { get; set; }
public int Entity2_Id { get; set; }
public int Entity3_Id { get; set; }
public string OtherData { get; set; }
public virtual Entity2 Entity2 { get; set; }
public virtual Entity3 Entity3 { get; set; }
}
public Entity2
{
public int Id { get; set; }
public virtual List<Entity1> Entity1s { get; set; }
}
public Entity3
{
public int Id { get; set; }
public virtual List<Entity1> Entity1s { get; set; }
}
public class Entity1Config : EntityTypeConfiguration<Entity1>
{
HasKey(k => new { k.MorePK, k.Entity2_Id, k.Entity3_Id });
HasRequired(p => p.Entity2)
.WithMany()
.HasForeignKey(p => p.Entity2_Id);
HasRequired(p => p.Entity3)
.WithMany()
.HasForeignKey(p => p.Entity3_Id);
Property(x => x.Entity2_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Entity3_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
如果我注释掉行
public virtual List<Entity1> Entity1s { get; set; }
在ENTITY2和ENTITY3然后正确生成数据库,但我认为EF要求的导航性能吧?
什么是获得正确的数据库模式的正确方法是什么?
on Entity2 and Entity3 then it generates the DB correctly but I think EF requires the navigational properties right? What is the correct way to get the proper database schema?
推荐答案
我想它了!这个的hasMany加入外国实体CONFIGS:
I figured it out! Add this HasMany to the foreign entity configs:
public Entity2Config : EntityTypeConfiguration<Entity2>
{
HasMany(x => x.Entity1s)
.WithRequired(x => x.Entity2)
.HasForeignKey(x => x.Entity2_Id);
}
public Entity3Config : EntityTypeConfiguration<Entity3>
{
HasMany(x => x.Entity1s)
.WithRequired(x => x.Entity3)
.HasForeignKey(x => x.Entity3_Id);
}
这篇关于如何创建实体框架中使用两个外键5码第一个主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!