【问题标题】:Owned Type in EF Core with optional navigation具有可选导航的 EF Core 中的自有类型
【发布时间】:2020-11-17 11:26:33
【问题描述】:

下面是我的课

class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
   
    public int? CityId { get; set; }
    public City City { get; set; }
  
     public int CountryId { get; set; }
    public Country Country { get; set; }
}


public class City
{
   public int Id { get; set; }
  public string Name { get; set; }
}

我的问题是:

  1. 我可以将 Address 类设为 OwnedType,因为 City id 是可选的

  2. 如果我将 Address 设为拥有类型,那么我的 City 类也需要拥有类型?

提前致谢使用 ef 核心 3.1

【问题讨论】:

    标签: asp.net-core ef-core-3.1


    【解决方案1】:

    您可以像这样将您的 Address 类设置为 OwnedType。

    地址类:

    public class Address
    {
        public string Street { get; set; }
        public int? CityId { get; set; }
        public City City { get; set; }
        public Company Company { get; set; }
    }
    

    公司类别:

    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }     
        public Address Address { get; set; }
    }
    

    流利的 API:

    public class YourDbContext : DbContext
    {
        public YourDbContext (DbContextOptions<YourDbContext> options)
            : base(options)
        {
        }
    
        //Note:no need add Address DbSet
    
        public DbSet<City> City { get; set; }
        public DbSet<Company> Company { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Company>().OwnsOne(c => c.Address);
        }
    }
    

    如果我将 Address 设为拥有类型,那么我的 City 类也需要拥有类型?

    您的 City 类不需要是拥有类型。

    参考:

    https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities#explicit-configuration

    结果:

    配置自有类型时,companyaddress生成一张表,城市id可以设置也可以不设置。如果要设置城市id,需要在其中插入一条新记录你的city 表。

    【讨论】:

    • 谢谢...cityid 在地址中是可选的...我可以将地址设置为拥有类型的仪式吗?
    • 您好,您的意思是可以设置或不设置cityid?
    • Yes..cityid 在地址中是可选的(有些公司可能没有 city )。
    • 其实,我所做的是让您的要求成真。检查我的解释。确保您使用的是自有类型。地址类不能有 DbSet。
    • 我不知道我错过了什么,我无法让它工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2021-04-28
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多