Reputation: 1
I am trying to figure out how to setup the navigation properties for 2 models (entities) that will generate the SQL tables. The scenario: I have a shipment and a company model/entity. I need to tie 3 properties ClientID¸ ShipperID and ConsigneeID from the Shipment model to point to CompanyID in the Company model. Now what are the correct Navigation Properties for the Shipment model and what the Context is going to look like?
public virtual ICollection< Company > Companies { get; set; }
OR
public virtual Company Company { get; set; }
Here are the 2 models:
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; }
}
Upvotes: 0
Views: 1071
Reputation: 21366
if your shipment have many companies you need to use (many to many relationship)
public virtual ICollection< Company > Companies { get; set; }
else if your shipment have only one company you need to use (one to many relationship)
public virtual Company Company { get; set; }
And optionally you can to specify more about the relationship in onModelBuilding
event in your dbContext.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Shipment>()
.HasRequired(x => x.Company ) \\..... etc as your requirement
Upvotes: 2
Reputation: 623
You'll need to use some Attributes to accomplish this. I'm assuming that you have a 1-* relation between shipments and companies. (A shipment to * Clients/Shippers/Consignees) Shipment:
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; }
}
Company:
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; }
}
The Context:
public class TesteEntityMVCContext : DbContext
{
public DbSet<Shipment> Shipments { get; set; }
public DbSet<Company> Companies { get; set; }
}
Upvotes: 2