实体框架4 / MVC3导航属性困境

时间:2011-07-30 02:30:57

标签: entity-framework asp.net-mvc-3

我试图弄清楚如何为将生成SQL表的2个模型(实体)设置导航属性。场景:我有货物和公司模型/实体。我需要将Shipment模型中的3个属性ClientID¸ShipperID和ConsigneeID绑定到公司模型中的CompanyID。现在什么是Shipment模型的正确导航属性以及Context将会是什么样子?

    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 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您需要使用一些属性来完成此任务。 我假设您与货物和公司之间存在1- *关系。 (发往*客户/托运人/收货人) 装运:

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; }
}