将数据库数据拆分为 class 和 subclass

Splitting database data into class and subclass

假设现在我在数据库中有一个 table,具有这些字段:

属性

id
num_bedrooms
num_bathrooms
num_garages
latitude
longitude
street_1
street_2
street_3
suburb
city
region
country

现在我想使用 EF Core 从我的 ASP .Net Core Web API 对其进行增删改查。所以我为它创建了一个模型,但我想为地址创建一个单独的 class:

public class Address
{
    [Column("latitude")]
    public double Latitude { get; set; }

    [Column("longitude")]
    public double Longitude { get; set; }

    [Column("street_1")]
    public string Street1 { get; set; }

    [Column("street_2")]
    public string Street2 { get; set; }

    [Column("street_3")]
    public string Street3 { get; set; }

    [Column("suburb")]
    public string Suburb { get; set; }

    [Column("city")]
    public string City { get; set; }

    [Column("region")]
    public string Region { get; set; }

    [Column("country")]
    public string Country { get; set; }
}

public class Property
{
    [Column("num_bedrooms")]
    public int NumBedrooms { get; set; }

    [Column("num_bathrooms")]
    public int NumBathrooms { get; set; }

    [Column("num_garages")]
    public int NumGarages { get; set; }

    public Address StreetAddress { get; set; }
}

有没有可能做这样的事情?当我尝试像这样在 API 控制器中对数据库执行读取时:

public DbSet<InspectionsData.Models.Property> Properties { get; set; }

// GET: api/Properties
Authorize]
[HttpGet]
public async Task<IActionResult> GetProperty()
{
    return Ok(_context.Properties);
}

我收到这个错误:

"The entity type 'Address' requires a primary key to be defined."

现在,我可以将 "Id" 添加到地址 class,但它不会真正映射到数据库中的任何内容...我这样做对吗?

您的 class 地址没有主键。 您应该添加 属性

[Key]
public int Id {get;set;}

或者设置已经存在的 属性 作为主键 [Key]

我也看到 class 属性 你会收到同样的信息。