[英]Code First : Unable to create 1 to many relationship. Creates 0…1 to many instead
Customer 顾客
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; }
}
Product 产品
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; }
}
Review 评论
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; }
}
} }
Generated model 生成模型
I want the relationship between Review and Customer to 1 to many not 0..1 to many. 我希望“评论”与“客户”之间的关系为1对多而不是0..1对多。 Each review must belong to one customer. 每个评论必须属于一个客户。 I don't understand how the relationship is mapped properly for Review - Product but not for the customer. 我不了解如何为“评论-产品”而不是为客户正确映射关系。
i only used Customer
and Review
models since those are the once you wanted an answer. 我只使用“ Customer
和“ Review
模型,因为这是您一次想要的答案。 Following is the your model classes should be. 以下是您的模型类应该是的。
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; }
}
this way you can have customers Review collection and cast it in to a list if you want.use Include()
method in your linq query to lazy load the customers review collection. 这样,您可以让客户评论集合并将其投射到列表中。使用linq查询中的Include()
方法来延迟加载客户评论集合。 for an example: 例如:
var customer = dbContext.Customer.Include("Reviews").where(x => x.Email == "john@gmail.com").FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.