[英]Joining two tables with one to many relatipnship in entity framework code first
[英]Entity Framework Code First creates classes from two tables and relationships one to many
我创建了一个应用程序,并以测试示例为例,列出了一张订单表。 我对类建模有疑问。
我有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,订单价值,汽车ID和所购买零件的ID。
我希望Car和Part表没有有关订单的数据。 我只想在应用程序中添加零件或汽车,以后只能在订购部分中从中进行选择。
让我们从您需要的物理表开始:
Part { Id, Name, Price }
Car { Id, Name, Price }
Order { Id }
OrderPart* { OrderId, PartId }
OrderCar* { OrderId, CarId }
最后两个表称为“联接表”,因为您需要它们能够以相同的顺序存储多个零件和多个汽车,但实际上并不是您认为属于模型的表。
如果您按以下方式设置类,那么实体框架将自动创建这些联接表:
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; }
}
请注意,“汽车”和“零件”表上的ICollection <>属性将成为创建连接表所需的EF线索。 另外,请记住,导航属性上需要“虚拟”。
这是好榜样吗?
这是我的课:
public class Suace
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Pizza
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public ICollection<Idgredient> Idgredients { get; set; }
public Sauce Sauce {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> Suace { get; set; }
public virtual ICollection<Part> Pizza { get; set; }
}
public class Idgredient
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Pizza> Pizzas { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.