【发布时间】:2023-03-19 12:53:02
【问题描述】:
客户
public class Customer
{
public Customer()
{
Addresses = new List<Address>();
Reviews = new List<Review>();
Products = new List<Product>();
}
[Key]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public Address DefaultAddress { get; set; }
public int DefaultAddressId { get; set; }
public List<Address> Addresses { get; set; }
public List<Review> Reviews { get; set; }
public List<Product> Products { get; set; }
}
产品
public class Product
{
public Product()
{
Reviews = new List < Review >();
}
public int Id { get; set; }
public Category Category { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public List<Review> Reviews { get; set; }
public List<Customer> Customers { get; set; }
}
评论
public class Review
{
public int Id { get; set; }
public string Text { get; set; }
public int Stars { get; set; }
[Required]
public int ProductId { get; set; }
[Required]
public string CustomerId { get; set; }
}
}
生成的模型
我希望评论和客户之间的关系是一对多而不是 0..1 对多。每条评论必须属于一个客户。我不明白如何正确映射关系以用于 Review - Product 但不适用于客户。
【问题讨论】:
-
可能是因为客户的键是一个字符串,可以为空?我总是使用不可为空的类型作为键。
-
@oerkelens 在这种情况下 customerId 是电子邮件,因为它对于每个客户都是唯一的。它必须是一个字符串。
-
从不,我重复从不使用字符串作为 PK。它会以泪水告终!确保为电子邮件设置唯一约束,但使用正确的类型,如 int、guid。
-
电子邮件必须是字符串。技术唯一键永远不必是字符串。甚至为主键分配功能意义通常被认为是不好的做法。
-
将客户表的 id 更改为 int 已修复。谢谢:)
标签: c# .net entity-framework entity-framework-6 ef-code-first