【发布时间】:2020-06-27 23:38:00
【问题描述】:
我正在使用 ASP.NET Core 和 Entity Framework Core,以及用于我的 react 应用数据库连接的控制器 API。
我有 4 个班级 Customer、Product、Store 和 Sales。 Customer、Product 和 Store 表与销售额是一对多的关系。
销售类
public class Sales
{
[Key]
public int SalesId { get; set; }
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int StoreId { get; set; }
[DataType(DataType.Date)]
public string DateSold { get; set; }
public Product Product { get; set; }
public Customer Customer { get; set; }
public Store Store { get; set; }
}
客户类别
public class Customer
{
[Key]
public int CustomerId { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Name { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Address { get; set; }
public IList<Sales> Sales { get; set; }
}
其他产品和商店与客户类相同。
我运行了迁移命令,但没有创建数据库并且命令运行成功,所以我创建了数据库,然后我运行了 update-database,它在数据库中创建了所有表。
如果我将导航属性添加到表中,它将根据销售记录中的 ID 获取包含客户、产品和商店记录的销售记录。
我想获取销售记录,在销售表中有客户、产品和商店 ID。如何获取他们的记录?
我的表格如下所示:
【问题讨论】:
-
有几种方法可以做到这一点,但我喜欢使用外键,它将 id 绑定到“虚拟”表:entityframeworktutorial.net/code-first/…(你应该让整数可以为空......所以"public int?ProductId { get; set; }")
-
@Dale K 我确实在依赖实体的导航属性上尝试了这个 [ForeignKey],但它没有创建导航属性。我会试试校长
-
@Dale K 我在依赖实体的导航属性上尝试了 [ForeignKey],现在我在销售表中有外键,但没有导航属性
-
我认为您的意思是标记@pcalkins,因为我没有为这个问题做出贡献。
-
哦对不起@pcalkins 和@Dale K
标签: sql-server asp.net-core entity-framework-core