【发布时间】:2017-12-03 00:20:07
【问题描述】:
现在假设我在数据库中有一个表,其中包含以下字段:
属性
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 对它进行 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 类添加一个“Id”,但它不会真正映射到数据库中的任何内容...我这样做对吗?
【问题讨论】:
-
您需要为该实体定义键,您可以通过两种方式做到这一点:第一种使用数据注释,第二种使用流畅的 api
标签: asp.net-core-mvc entity-framework-core asp.net-core-1.1