C# EF Core-使用外键连接两个表
我有两个EF核心实体,我想通过一个字符串键连接,这不符合id名称约定。下面是一个简单的DbContext:C# EF Core-使用外键连接两个表,c#,entity-framework-core,foreign-keys,C#,Entity Framework Core,Foreign Keys,我有两个EF核心实体,我想通过一个字符串键连接,这不符合id名称约定。下面是一个简单的DbContext: public DbSet<Entity1> Table1 { get; set; } public DbSet<Entity2> Table2 { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<E
public DbSet<Entity1> Table1 { get; set; }
public DbSet<Entity2> Table2 { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity1>()
.HasOne(s => s.Entity2)
.WithOne()
.HasForeignKey<Entity1>(s => s.Name);
}
public class Entity1
{
public String Name{ get; set; }
public Entity2 Entity2 { get; set; }
}
public class Entity2
{
[Key]
public String Nummer { get; set; }
}
public DbSet Table1{get;set;}
公共数据库集表2{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity()
.HasOne(s=>s.Entity2)
.WithOne()
.HasForeignKey(s=>s.Name);
}
公共类实体1
{
公共字符串名称{get;set;}
公共实体2实体2{get;set;}
}
公共类实体2
{
[关键]
公共字符串Nummer{get;set;}
}
它不会抛出任何错误-但在查询数据时,“Entity2”属性始终为空-即使表2中存在数据集,其中“numer”等于Entity1的“Name”值
我还尝试了ForeignKey属性,但没有OnModelCreating代码,但结果相同
我认为,我对EF核心中的外键概念存在完全的误解
有什么想法或提示吗?问题可能在查询过程中。如何查询数据。默认情况下,除非通过
Include()
显式指定,否则EFCore不会进行联接查询。比如说,
var entity1=db.Table1
.其中(x=>x.Name==“测试”)
.Include(x=>x.Entity2)x.Entity2)
指定两个表之间有一个连接查询,返回的Entity1
对象包含Entity2的数据,这就是问题所在:-)我想EF Core中会有一些神奇的东西为我这样做;-)非常感谢。