C# .net 5 - 由多个实体拥有的 OnModelCreating 实体

问题描述

当涉及多个实体拥有一个类时,我在理解 Fluent API 时遇到问题。

错误

The type 'City' cannot be configured as non-owned because an owned entity type with the same name already exists.

我有三个实体; CountryCityUser

CountryCity 通过从文件迁移获得 HasData() 方法的种子。 User 由最终用户创建,City 属性可以是 null

public class Country : Entity
{
    public List<City> Cities { get; init; }

    public Country()
    {
        Cities = new List<City>();
    }

}


public class City : Entity
{
    public int CountryID { get; set; }
    public Country Country { get; set; }
    public string Name { get; set; }
    public List<User> Users { get; init; }
    public City()
    {
        Users = new List<User>();
    }

}



public class User : Entity
{
    public int CityID { get; set; }
    public City City { get; set; }
}

现在我的基本 OnModelCreating 包含:

    builder.Entity<Country>(c =>
    {
        c.HasData(countriesList.ToArray());

        c.OwnsMany(x => x.Cities)
            .HasData(LoadCities(countryToLoadCities));
    });

但我不确定如何编写它以根据需要理解“User.City属性。我已经尝试了多个选项,包括直接导航属性、外键 + 导航属性UserCity间的对象。但是迁移总是按照我的方式抛出错误,我不确定它想让我做什么。

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Ignore<Entity>();

    //Load all country codes
    Country countryToLoadCities = null;
    var countriesList = LoadCountries(out countryToLoadCities);
    
    builder.Entity<Country>(c =>
    {
        c.HasData(countriesList);
        var b = c.OwnsMany(x => x.Cities);
        b.WithOwner().HasForeignKey(x => x.CountryID);
        b.HasData(LoadCities(countryToLoadCities));
        b.Ignore(x => x.Users);
        //b.OwnsMany(x => x.Users).WithOwner().HasForeignKey(f => f.CityID);

    });

    builder.Entity<Guild>(g => {
        g.OwnsMany(x => x.Channels).WithOwner().HasForeignKey(q => q.GuildID);
        var userBuilder = g.OwnsMany(x => x.Users);
        userBuilder.WithOwner().HasForeignKey(q => q.GuildID);
        userBuilder.HasOne(u => u.City).WithMany().HasForeignKey(q => q.CityID);

    });
}

解决方法

  1. 为什么需要从实体派生?这些是 POCO 课程。
  2. User 和 City 是一对多的关系,对吧?那么城市需要有用户列表。
  3. 在一对多实体中,除了对象本身之外,通常还有 ID 字段。因此,City 将具有 CountryId。

可能,也放置您的 DbContext 类。并且“实体只是具有 ID 的父级”。嗯?以及如何生成此 ID - 除了 CityID、CountryID 等?你真是自找麻烦

建议。我通常创建一个包含所有表和外键的数据库 - 然后运行脚手架来获取对象的基线。简化了很多!

然后从该模型开始,并进行所需的更改(如果有)。根据您的代码,我什至不确定您是否需要进行任何更改!