C# 如何首先在Entity Framework 5代码中使用两个外键创建主键?
我有一个实体,其中主键由另外两个表的两个外键组成。我有以下配置,但该表是由两个FK引用生成的 下表:C# 如何首先在Entity Framework 5代码中使用两个外键创建主键?,c#,foreign-keys,entity-framework-5,composite-primary-key,C#,Foreign Keys,Entity Framework 5,Composite Primary Key,我有一个实体,其中主键由另外两个表的两个外键组成。我有以下配置,但该表是由两个FK引用生成的 下表: 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) Entit
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)
产生于:
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);
}
公共实体1
{
公共int-MorePK{get;set;}
public int Entity2_Id{get;set;}
public int Entity3_Id{get;set;}
公共字符串OtherData{get;set;}
公共虚拟实体2实体2{get;set;}
公共虚拟实体3实体3{get;set;}
}
公共实体2
{
公共int Id{get;set;}
公共虚拟列表Entity1s{get;set;}
}
公共实体3
{
公共int Id{get;set;}
公共虚拟列表Entity1s{get;set;}
}
公共类Entity1配置:EntityTypeConfiguration
{
HasKey(k=>new{k.MorePK,k.Entity2_Id,k.Entity3_Id});
HasRequired(p=>p.Entity2)
.有很多
.HasForeignKey(p=>p.Entity2_Id);
HasRequired(p=>p.Entity3)
.有很多
.HasForeignKey(p=>p.Entity3_Id);
属性(x=>x.Entity2_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
属性(x=>x.Entity3_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
如果我把这行注释掉
public virtual List<Entity1> Entity1s { get; set; }
公共虚拟列表Entity1s{get;set;}
在Entity2和Entity3上,它会正确地生成DB,但我认为EF需要导航属性,对吗?
获取正确的数据库模式的正确方法是什么?我找到了!将此HasMany添加到外部实体配置:
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);
}
公共Entity2Config:EntityTypeConfiguration
{
HasMany(x=>x.Entity1s)
.WithRequired(x=>x.Entity2)
.HasForeignKey(x=>x.Entity2_Id);
}
公共Entity3Config:EntityTypeConfiguration
{
HasMany(x=>x.Entity1s)
.WithRequired(x=>x.Entity3)
.HasForeignKey(x=>x.Entity3_Id);
}