客户
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; }
}
}
生成的模型
我希望“评论”与“客户”之间的关系为1对多而不是0..1对多。每个评论必须属于一个客户。我不了解如何针对“评论-产品”而不是针对客户正确映射关系。
答案 0 :(得分:0)
我只使用了Customer
和Review
模型,因为那是您一次想要的答案。
以下是您的模型类别。
public class Customer
{
public Customer()
{
Reviews = new HashSet<Review>();
}
[Key]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public ICollection<Review> Reviews { 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; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
通过这种方式,您可以让客户查看评论集并将其投射到列表中。在linq查询中使用Include()
方法来延迟加载客户评论集。
例如:
var customer = dbContext.Customer.Include("Reviews").where(x => x.Email == "john@gmail.com").FirstOrDefault();