How do I create a POCO object that has 2 references to another class

允我心安 提交于 2019-12-24 09:49:15

问题


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).



来源:https://stackoverflow.com/questions/5904796/how-do-i-create-a-poco-object-that-has-2-references-to-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!