3

I am creating a schema where the following logic applies:

  • A String can belong to multiple locations.
  • Multiple Locations can have multiple String, or no String.
  • The DateTime (As DateScraped) at which the relationship between Location and String was formed must be recorded.

Basically, I've mapped the relationship as a many-to-many relationship using a junction table like so:

sqldbm

In mapping the chart in Code First EF6 (Using SQLite), I have the following objects:

public class Location
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long LocationId { get; set; }

    [Required]
    public string Country { get; set; }

    [Required]
    public string CityOrProvince { get; set; }

    [Required]
    public string PlaceOrCity { get; set; }

    [Required]
    public string PostalCode { get; set; }
}

public class String
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long StringId { get; set; }

    [Required]
    public string SearchString { get; set; }
}

public class LocationStringMapping
{
    [Required]
    public string LocationId { get; set; }

    [Required]
    public string StringId { get; set; }

    [Required]
    public DateTime DateScraped { get; set; }
}

I've based what I've done so far on conjecture as I cannot seem to find any concrete information on how a relationship such as this must be built. Normally I'd use a junction table, but that is in vanilla SQL. Is the implementation different in EF?

Am I going to have to cumbersomely manage the LocationStringMapping table by hand or is there some kind of implicit relationship model I don't know about?

Bitz
  • 1,128
  • 11
  • 33
  • I think [this article](https://msdn.microsoft.com/en-us/library/jj713564(v=vs.113).aspx) might help. They key terminology is navigation properties. Also, [this answer](https://stackoverflow.com/a/37115700/2557128) may be helpful. – NetMage May 24 '18 at 20:42

1 Answers1

4
public class Location
{
    public long LocationId {get;set;}
    public virtual ICollection<LocationStringMapping> LocationStringMappings {get;set;}
    //other
}

public class String
{
    public long StringId {get;set;}
    public virtual ICollection<LocationStringMapping> LocationStringMappings {get;set;}
    //other
}

public class LocationStringMapping
{
    [Key, Column(Order = 0)]
    public long LocationId { get; set; }
    [Key, Column(Order = 1)]
    public long StringId { get; set; }

    public virtual Location Location {get;set;}
    public virtual String String {get;set;}

    public DateTime DateScraped {get;set;}
}
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • Thank you! I didn't expect implicit relationships like this to be so simple, but upon testing your solution, it worked as expected! – Bitz May 25 '18 at 18:38