ef code first - Entity Framework Many to Many Relation on same entity with additional parameters -


i have city entity:

public class city     {         public int id { get; set; }          public string name { get; set; }          public virtual icollection<citydistance> citydistances { get; set; }      } 

and keep distances between cities.
1. how can achieve in code first entity framework 6?

here other classes:

 public class citydistance     {         [key, column(order = 0)]         public int cityaid { get; set; }         [key, column(order = 1)]         public int citybid { get; set; }         public virtual city citya { get; set; }         public virtual city cityb { get; set; }          public double distance { get; set; }     } 
  1. is correct design?

when run "add-migration distances" here result.
3. why adding foreign key column named "city_id"?

createtable(                 "dbo.citydistances",                 c => new                     {                         cityaid = c.int(nullable: false),                         citybid = c.int(nullable: false),                         distance = c.double(nullable: false),                         city_id = c.int(),                     })                 .primarykey(t => new { t.cityaid, t.citybid })                 .foreignkey("dbo.cities", t => t.city_id)                 .foreignkey("dbo.cities", t => t.cityaid, cascadedelete: true)                 .foreignkey("dbo.cities", t => t.citybid, cascadedelete: true)                 .index(t => t.cityaid)                 .index(t => t.citybid)                 .index(t => t.city_id);   

that's because ef acting simple bookkeeper: citya, cityb, that's 2 foreign keys, citydistances, that's foreign key, makes 3 foreign keys.

ef doesn't know intend citydistances other (inverse) end of association either citya or cityb. have indicate explicitly, either data annotations:

public class city {     ...      [inverseproperty("citya"]     public virtual icollection<citydistance> citydistances { get; set; }  } 

or fluent mapping:

modelbuilder.entity<city>()             .hasmany(c => c.citydistances)             .withrequired(cd => cd.citya)             .hasforeignkey(cd => cd.cityaid); 

(by implicitly that, yes, correct design, @ least technically).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -