How do I create a POCO object that has 2 reference

2019-08-01 10:29发布

问题:

I have a table (Event) that can have 2 Locations (main, alternate). Locations can be used in other tables (so no EventId in the locationTable) Using POCO self-tracking, how do I create the reference from the Event table to the Locations table, or what is the best way to handle this situation (I'm having a total brain freeze over this)? (.NET 4.0 C#, EF4.1, MVC 3 being used).

Simplified classes:

public class Event
{
   public int EventId {get; set;}
   public string Tile {get; set;}
   public int MainLocationId {get; set;}
   public int AltLocationId {get; set;}

   public virtual ICollection<Location> EventLocations {get; set;}
}

public class Location
{
   public int LocationId {get; set;}
   public string Name {get; set;}
}

I was thinking a linking table (EventLocations) with the PK of each table and a flag indicating if it's the main or alt location, but I'm not sure how this would look in a POCO class setup. Maybe this, but it requires extra business logic (and I ultimately would like to be able to incorporate this king of solution into a T4 so I don't have to add business logic in future projects):

public class Event
{
   public int EventId {get; set;}
   public string Tile {get; set;}

   public virtual ICollection<EventLocation> EventLocations {get; set;}
}

public class Location
{
   public int LocationId {get; set;}
   public string Name {get; set;}

   public virtual ICollection<EventLocation> EventLocations {get; set;}
}

public class EventLocation
{
   public int EventId {get;set;}
   public int LocationId {get;set;}
   public bool IsMain {get; set;}

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

Thanks for any advice/ tips/ solutions/ constructive criticism!

回答1:

The simplest way is simply using:

public class Event
{
   public int EventId {get; set;}
   public string Tile {get; set;}
   public int MainLocationId {get; set;}
   public int AltLocationId {get; set;}

   public virtual Location MainLocation {get; set;}
   public virtual Location AlternativeLocation {get; set;}

   // You can also add Foreign key properties for locations to simplify some usage scenarios
}

public class Location
{
   public int LocationId {get; set;}
   public string Name {get; set;}
}

You have exact number of locations defined for your event so using many-to-many relation is probably not needed (it can accidentally add more locations to your Event).