C# EF核心代码首次迁移:“;无法为一对一关系确定子女/受抚养方”;
我正在进行代码优先迁移到我的PostgreSQL数据库。我已经根据我看到的一些例子配置了我的关系,但是我被下面的错误难住了 引发异常:Microsoft.EntityFrameworkCore.dll中的“System.InvalidOperationException” Microsoft.EntityFrameworkCore.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理 无法确定“ecommercecontent.identification”和“ecommercecontent.identification.ecommercecontent”之间的一对一关系的子方/从属方。要标识关系的子/依赖方,请配置外键属性。如果这些导航不应属于同一关系的一部分,请在不指定反向的情况下对其进行配置。有关更多详细信息,请参阅 下面是我的代码示例,为了简洁起见,我删去了一些东西 以下是有问题的两类:C# EF核心代码首次迁移:“;无法为一对一关系确定子女/受抚养方”;,c#,postgresql,entity-framework-core,C#,Postgresql,Entity Framework Core,我正在进行代码优先迁移到我的PostgreSQL数据库。我已经根据我看到的一些例子配置了我的关系,但是我被下面的错误难住了 引发异常:Microsoft.EntityFrameworkCore.dll中的“System.InvalidOperationException” Microsoft.EntityFrameworkCore.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理 无法确定“ecommercecontent.iden
public class ecommercecontent
{
[Key]
public int ecommercecontentid { get; set; }
public string productnameenglish { get; set; }
public string productnamefrench { get; set; }
public string brandnameenglish { get; set; }
public string brandnamefrench { get; set; }
public ecommercecontentidentification identification { get; set; }
}
public class ecommercecontentidentification
{
[Key]
public int ecommercecontentidentificationid { get; set; }
public DateTimeOffset archivedate { get; set; }
public DateTimeOffset dateupdated { get; set; }
public DateTimeOffset startdate { get; set; }
public DateTimeOffset systemversion { get; set; }
public ecommercecontent ecommercecontent { get; set; }
}
下面是我的DbContext
类,它具有OnModelCreating
覆盖:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ecommercecontent>()
.HasOne(a => a.identification)
.WithOne(b => b.ecommercecontent)
.OnDelete(DeleteBehavior.Cascade);
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity()
.HasOne(a=>a.identification)
.WithOne(b=>b.电子商务内容)
.OnDelete(DeleteBehavior.Cascade);
}
你知道我做错了什么吗?当你有一对一的关系时,你需要告诉英孚哪个是依赖关系。例如,如果
ecommercontentification
是依赖项,则需要添加此行
modelBuilder.Entity<ecommercecontent>()
.HasOne(a => a.identification)
.WithOne(b => b.ecommercecontent)
.HasForeignKey<ecommercecontentidentification>(e => e.{{foriegn key property}})
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity()
.HasOne(a=>a.identification)
.WithOne(b=>b.电子商务内容)
.HasForeignKey(e=>e.{{ForeignKey属性}})
.OnDelete(DeleteBehavior.Cascade);
我不知道这两个表之间共享了什么键。您的
ecommercontentification
上需要有ecommercontentid
,反之亦然。您可以定义.HasOne(…)。从关系的任何一方开始,使用一个(…)
。是.HasForeignKey(…)
告诉fluent api哪个是主api,哪个是依赖api。这就成功了。我按照您的建议添加了新字段(ecommercontentification.ecommercontentid),然后使用HasForeignKey方法选择该新字段作为外键。