【问题标题】:Code First : Unable to create 1 to many relationship. Creates 0...1 to many instead代码优先:无法创建一对多关系。改为创建 0...1 到多个
【发布时间】: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


【解决方案1】:

我只使用了CustomerReview 模型,因为这些模型是您想要的答案。 以下是您的模型类应该是。

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();

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多