![](/img/trans.png)
[英]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.