2011-07-30 71 views
0

我想弄清楚如何设置将生成SQL表的2个模型(实体)的导航属性。场景:我有一个货件和一个公司模型/实体。我需要将Shipment模型中的3个属性ClientIDF ShipperID和ConsigneeID绑定到公司模型中的CompanyID。现在什么是Shipment模型的正确导航属性以及Context将会是什么样子?实体框架4/MVC3导航属性困境

public virtual ICollection<Company> Companies { get; set; } 
     OR 
    public virtual Company Company { get; set; } 

这里有2种型号:

public class Shipment 
{ 
    public int ShipmentID { get; set; } 
    public string Name { get; set; } 
    public DateTime DateStamp { get; set; } 
    public int ClientID { get; set; } 
    public int ShipperID { get; set; } 
    public int ConsigneeID { get; set; } 

    public virtual ICollection<Company> Companies { get; set; } 
     OR 
    public virtual Company Company { get; set; } 
} 

public class Company 
{ 
    public int CompanyID { get; set; } 
    public string Name { get; set; } 
    public DateTime DateStamp { get; set; } 

    public virtual ICollection<Shipment> Shipments { get; set; } 
} 

回答

2

,如果你的货有你需要使用许多公司(多对多的关系)

public virtual ICollection<Company> Companies { get; set; } 

否则,如果您的货只有一个您需要使用的公司(一对多关系)

public virtual Company Company { get; set; } 

还可以选择在dbContext中指定更多关于onModelBuilding事件中的关系。

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Shipment>() 
    .HasRequired(x => x.Company) \\..... etc as your requirement 
2

您将需要使用一些属性来完成此操作。 我假设您在出货量和公司之间有1 *关系。 (A货为*客户端/托运人/收货人) 装运:

public class Shipment 
{ 
    public int ShipmentID { get; set; } 
    public string Name { get; set; } 
    public DateTime DateStamp { get; set; } 
    [ForeignKey("Client")] 
    public int ClientID { get; set; } 
    [ForeignKey("Shipper")] 
    public int ShipperID { get; set; } 
    [ForeignKey("Consignee")] 
    public int ConsigneeID { get; set; } 

    public virtual Company Client { get; set; } 
    public virtual Company Shipper { get; set; } 
    public virtual Company Consignee { get; set; } 
} 

公司:

public class Company 
{ 
    public int CompanyID { get; set; } 
    public string Name { get; set; } 
    public DateTime DateStamp { get; set; } 
    [InverseProperty("Shipper")] 
    public virtual ICollection<Shipment> ShipmentsShipped { get; set; } 
    [InverseProperty("Consignee")] 
    public virtual ICollection<Shipment> ShipmentsConsigned { get; set; } 
    [InverseProperty("Client")] 
    public virtual ICollection<Shipment> ShipmentsOwned { get; set; } 
} 

的语境:

public class TesteEntityMVCContext : DbContext 
{  
    public DbSet<Shipment> Shipments { get; set; } 
    public DbSet<Company> Companies { get; set; } 
} 
+0

切记要以此为答案,如果解决了你问题! –