Dylan Erskine Dylan Erskine - 2 months ago 8
ASP.NET (C#) Question

How to make a one to seven relationship, with only one of the seven types in each - Entity-Framework

I have a model called "Week" that has a list of "Day" and a day has an Enum "DayOfWeek" which has "Monday", "Tuesday", "Thursday", "Friday" and "Sunday"

"Week" Model



public class Week
{
public string Id { get; set; } = Guid.NewGuid().ToString();
//This needs to be only able to have one "Monday" one "Tuesday" etc
public virtual List<Day.Day> DaysOfTheWeek { get; set; }
}


"Day" Model



public class Day
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public Week.Week Week { get; set; }
//This is my key (for "week") each week should only have one "Monday", one "Tuesday", etc
public DayOfWeek DayOfWeek { get; set; }
public virtual List<Class.Class> Classes { get; set; }
}


Each "Week" should only be able to have one of each of the types of "Day", one "Monday", one "Tuesday", one "Wednesday" etc

How can I achieve this with data annotations/relationships

Thanks, From Dylan

Answer

I think you can achieve this in two ways:

  1. Using validation only

Implement IValidatableObjectand check the uniqueness of days in there.

  1. Using a composite primary key on Day, which includes the Week ID and the DayOfWeek.

This will put the constraint on the physical model and conceptually make Day a "child entity" of Week.

You can do something like this (you may need to adjust, I didn't have time to try it out):

public class Day
{
  public Week.Week Week { get; set; }
  [Key] 
  [Column(Order = 2)] 
  public DayOfWeek DayOfWeek { get; set; }
  public virtual List<Class.Class> Classes { get; set; }

  [Key] 
  [Column(Order=1)] 
  // Helper for PK; EF will recognize this as the FK by convention
  public string WeekId { get; set; }
}

You can also do a similar configuration via the fluent interface instead of using the attributes.