我试图在程序包管理器控制台中使用“ 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.


我的模型类如下所示:

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; }
}


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

modelBuilder.Entity<Country>()
            .HasOne(a => a.CapitalCity)
            .WithOne(a => a.Country)
            .HasForeignKey<CapitalCity>(c => c.CountryID);


我有什么错误?

最佳答案

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

modelBuilder.Entity<Country>()
            .HasOne(a => a.CapitalCity)
            .WithOne(a => a.Country)
            .HasForeignKey<CapitalCity>(c => c.CountryID);

关于entity-framework - 不能确定 child /受抚养人之间的一对一关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51808912/

10-15 16:42