Asp.net core mvc 将数据库数据拆分为类和子类

Asp.net core mvc 将数据库数据拆分为类和子类,asp.net-core-mvc,entity-framework-core,asp.net-core-1.1,Asp.net Core Mvc,Entity Framework Core,Asp.net Core 1.1,假设现在数据库中有一个表,其中包含以下字段: 性质 现在,我想使用EF Core从我的ASP.NETCoreWebAPI中CRUD到它。所以我为它创建了一个模型,但我想为地址创建一个单独的类: public class Address { [Column("latitude")] public double Latitude { get; set; } [Column("longitude")] public double Longitude { get; se

假设现在数据库中有一个表,其中包含以下字段:

性质

现在,我想使用EF Core从我的ASP.NETCoreWebAPI中CRUD到它。所以我为它创建了一个模型,但我想为地址创建一个单独的类:

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);
}
我得到这个错误:

实体类型“Address”需要定义主键


现在,我可以向Address类添加一个Id,但它不会真正映射到数据库中的任何内容。。。我这样做对吗?

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

[Key]
public int Id {get;set;}
或使用[key]将已存在属性设置为主键


正如我所看到的,对于类属性,您将看到相同的消息。

您需要为该实体定义键,您可以通过两种方式来实现:第一种是使用数据注释,第二种是使用fluent api
[Key]
public int Id {get;set;}