entity framework - Code First design for 3 tables (one-to-one) -


i trying create database tracking parcel being mailed. stuck on trying figure out best way implement relationship between parcel , location @ given time/date. ultimately, need able @ moment in past , tell parcel , @ time/date. when entered location, , when left location.

i have 3 tables this. (shortened basics)

public class parcel {     public int parcelid { get; set; }      public virtual location location { get; set; } }  public enum locationtype {     warehouse, truck } public class location {     [key, foreignkey("parcel")]     public int parcelid { get; set; }     public locationtype locationtype { get; set; }      public virtual parcel parcel { get; set; } } locationtimedate {  } 

i not sure how relate locationtimedate location. think should one-to-one relationship. i'd have have locationid. location's key foreignkey (parcel).

am going correct way? thoughts/guidance appreciated.

this is, me, case many-to-many relationship additional information (location, timedate, , parcel). parcel can have many locations (at different times), , location might belong many parcels (at different times). hope understand correctly.

here suggested design:

public class parcel {     public int parcelid { get; set; }      public list<parcelassignment> parcelassignments { get; set; } }  public class location {     [key]     public int locationid { get; set; }      public locationtype locationtype { get; set; }      public list<parcelassignment> parcelassignments { get; set; } }  public enum locationtype {     warehouse, truck }   public class parcelassignment {     [key]     public int parcelassignmentid { get; set; }       [required]     public int locationid { get; set; }      [foreignkey("locationid")]     public location location { get; set; }       [required]     public int parcelid { get; set; }      [foreignkey("parcelid")]     public parcel parcel { get; set; }      public datetime dateofassignment { get; set; } } 

your fluent api goes dbcontext class:

modelbuilder.entity<parcelassignment>()             .hasrequired(pa => pa.parcel)             .withmany(p => p.parcelassignments)             .hasforeignkey(pa => pa.parcelid);  modelbuilder.entity<parcelassignment>()             .hasrequired(pa => pa.location)             .withmany(l => l.parcelassignments)             .hasforeignkey(pa => pa.locationid); 

you can read more many-to-many relationships on ef here:

https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-i/

https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-ii/


Popular posts from this blog