gpt4 book ai didi

c# - Entity Framework Code First 从两个表和一对多关系创建类

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:04 24 4
gpt4 key购买 nike

我创建了一个应用程序,作为测试示例,我使用了一张订单表。我对类建模有疑问。

我有 3 个类:

public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}


class Order
{
public Order()
{
Cars = new List<Car>();
Parts = new List<Part>();
}

public int OrderId { get; set; }

public int CarId { get; set; }
public int PartId { get; set; }

public ICollection<Car> Cars { get; set; }
public ICollection<Part> Parts { get; set; }
}

不知道这个模型好不好。你怎么认为?因为这里没有东西:/在应用程序中:

  • 我无法向数据库中没有的订单添加汽车或零件。

  • 在订单表中,我只想查看订单 ID、订单值(value)、汽车 ID 和所购零件的 ID。

我希望 Car 和 Part 表没有关于订单的数据。我只想在应用程序中添加零件或汽车,以后只能在订单部分从中选择。

最佳答案

让我们从您需要的物理表开始:

Part { Id, Name, Price }
Car { Id, Name, Price }
Order { Id }

OrderPart* { OrderId, PartId }
OrderCar* { OrderId, CarId }

最后两个表称为“连接表”,因为您需要它们能够存储同一订单上的多个零件和多辆汽车,但实际上并不是您认为是模型一部分的表。

如果您按如下方式设置类, Entity Framework 将自动生成这些连接表:

public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }

public virtual ICollection<Order> Orders { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }

public virtual ICollection<Order> Orders { get; set; }
}

class Order
{
public Order()
{
Cars = new List<Car>();
Parts = new List<Part>();
}

public int OrderId { get; set; }

public virtual ICollection<Car> Cars { get; set; }
public virtual ICollection<Part> Parts { get; set; }
}

请注意,Car 和 Part 表上的 ICollection<> 属性将成为 EF 需要创建连接表的线索。另外,请记住您的导航属性需要“虚拟”。

关于c# - Entity Framework Code First 从两个表和一对多关系创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com