如何在Address表中使用Countries查找表。 EF核心

时间:2017-10-02 01:20:15

标签: c# .net asp.net-core entity-framework-core

我正在尝试创建一个包含Country实体的Address表。 地址表只能包含1个国家/地区条目。我想要另一张包含国家列表的表格。在UI上我想要一个下拉列表,列出所有国家(位于Countries表中)。选择国家/地区后,将填充地址表中的国家/地区实体。

我不确定Address表和Country表之间的关系。在我看来,Countries表不是一个依赖表(独立)。

我不确定如何注释我的属性以获得所需的结果。

目前这是我的地址模型的样子。

public class Address
{
    [Key]
    [DatabaseGenerated( DatabaseGeneratedOption.Identity )]
    public int AddressId { get; set; }

    [Required]
    [MaxLength( 255 )]
    public string AddressLine1 { get; set; }

    [Required]
    [MaxLength( 50 )]
    public string Region { get; set; }

    [Required]
    public Country Country { get; set; }
}

国家模式。

public class Country
{
    [Key]
    [DatabaseGenerated( DatabaseGeneratedOption.Identity )]
    public int CountryId { get; set; }

    [Required]
    public string CountryName { get; set; }

    public Address Address { get; set; }

    [ForeignKey( nameof( AddressId ) )]
    public int AddressId { get; set; }
}

上下文

public sealed class LodgingCrmContext : DbContext
{
    public LodgingCrmContext( DbContextOptions<LodgingCrmContext> options ) 
        : base( options )
    {
    }

    public DbSet<Country> Countries { get; set; }
    public DbSet<Address> Addresses { get; set; }   
}

Country模型中的Address FK和Address导航属性对我没有意义。您不会从国家/地区导航到地址。此外,Countries表应该是一个独立的表,不依赖于Address表。我怎么能做到这一点?

我有点困惑,可以使用一些帮助。

0 个答案:

没有答案
相关问题