繁体   English   中英

无法确定一对一关系的子女/受抚养方

[英]The child/dependent side could not be determined for the one-to-one relationship

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

我的 Model 类如下所示:

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

只是指出,如果您真的不需要一对一的关系,您可以像这样解决它,并且迁移将开箱即用。 在此示例中,如果CapitalCity可以与不同的国家/地区共享相同的名称,则有效。 您当然需要考虑一个国家更改其首都城市名称但另一个国家没有更改的可能性。

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 class Country
{
    public int ID { get; set; }
    public string Name { get; set; }
    public long Population { get; set; }

    public List<CapitalCity> CapitalCities { get; set; } = new List<CapitalCity>();
}

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

    public int CountryID { get; set; }
    public Country Country { get; set; }
}

我认为这更好,因为许多国家/地区拥有或拥有多个首都城市。

https://en.wikipedia.org/wiki/List_of_countries_with_multiple_capitals

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM