Multiple Relationships Between Two Models

I use the first code and EF 4.1 im my MVC3 App and have two models that have two relationships between them. Here are the classes that apply to these models:

public class Cattle { public int CattleID { get; set; } public int FarmID { get; set; } public int SituationID { get; set; } public int DiscardID { get; set; } public int Stamp { get; set; } public string Sex { get; set; } public string Condition { get; set; } public virtual Farm Farm { get; set; } [InverseProperty("Cattles2")] public virtual ICollection<Farm> Farms { get; set; } } public class Farm { public int FarmID { get; set; } public string Name { get; set; } public virtual ICollection<Cattle> Cattles { get; set; } public virtual ICollection<Cattle> Cattles2 { get; set; } } 

One relationship is one to one or many of the reasons a catle can only be in a farm and a farm can contain a lot of cat. Another relationship is for many that catle can be passed between farms, and I will create a third table to store translations using the Fluent API. I would also like to add the Date property to the new table and don't know how to do it. Here is the code in the FarmContext inside the OnModelCreating method:

  modelBuilder.Entity<Catle>() .HasMany(c => c.Farms).WithMany(i => i.Catles) .Map(t => t.MapLeftKey("CatleID") .MapRightKey("FarmID") .ToTable("CatleTransfer")); 

When I build the project, it seems to be working fine, and the created Catle and Farm tables are powered by the FarmInitializer, but some information pointing to this relationship is not available on the Catle index page. it seems empty to me. Here is the code that receives the information:

 @Html.DisplayFor(modelItem => item.Farm.Name) 

I need to know what I am doing wrong, or if there is a more suitable method to solve this problem.

+4
source share
1 answer

You may need a specific relationship relationship when working with multiple associations.

Try adding the Foreign Key attribute to the Farm navigation property.

 [ForeignKey("FarmID")] public virtual Farm Farm { get; set; } 
0
source

All Articles