无法确定一对一关系的孩子/依赖方

A.M*_*A.M 22 entity-framework entity-framework-core

我试图在包管理器控制台中使用“update-database”命令更新我的数据库,但我遇到了这种错误:

The child/dependent side could not be determined for the one-to-one 
relationship between 'Country.CapitalCity' and 'CapitalCity.Country'. To 
identify the child/dependent side of the relationship, configure the foreign 
key property. If these navigations should not be part of the same 
relationship configure them without specifying the inverse. See 
http://go.microsoft.com/fwlink/?LinkId=724062 for more details.
Run Code Online (Sandbox Code Playgroud)

我的模型类如下所示:

public class Country
{
    public int ID { get; set; }
    public string Name { get; set; }
    public long Population { get; set; }

    public int CapitalCityID { get; set; }
    public CapitalCity CapitalCity { get; set; }
}

public class CapitalCity
{
    public int ID { get; set; }
    public int Name { get; set; }

    public int CountryID { get; set; }
    public Country Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

搜索有关此问题的信息后,我在 DbContextModelSnapshot 中添加了以下代码,但仍有问题。

modelBuilder.Entity<Country>()
            .HasOne(a => a.CapitalCity)
            .WithOne(a => a.Country)
            .HasForeignKey<CapitalCity>(c => c.CountryID);
Run Code Online (Sandbox Code Playgroud)

我有什么错误?

viv*_*una 27

您必须将以下代码放在 DBContext 类中,而不是放在 SnapShot 类中。不要修改 Snapshot 类,它是自动生成的类。

modelBuilder.Entity<Country>()
            .HasOne(a => a.CapitalCity)
            .WithOne(a => a.Country)
            .HasForeignKey<CapitalCity>(c => c.CountryID);
Run Code Online (Sandbox Code Playgroud)