How to define an MVC database structure using the same sub-table in different super-tables

梦想与她 提交于 2019-12-12 03:44:38

问题


I am making an hours calendar using MVC's Code First approach. This is the data-structure from the bottom-up:

All classes contain table element ID's.
A DaySpec contains opening and closing times for a day.
A WeekSpec contains, among trivial Booleans, an array of DaySpecs.
An ExceptionHoursSet, which defines hours that are exceptions to a general hours pattern, contains an integer RepCount and an object HoursSet; RepCount specifying how many times the exception is repeated, and the HoursSet being either a DaySpec or a WeekSpec.
A Schedule contains a string Name, a WeekSpec which specifies the general pattern on a weekly basis, and an IEnumerable of ExceptionHoursSets.

Right.

So my question is, using the WeekSpec class both in Schedule and ExceptionHoursSet, can I share it between the two in the database structure? How would I set up the EF relationships?


回答1:


Sure they can!

If you are doing this using Entity Framework's Code First approach, you would simply include the foreign key relationships as types within a class:

public class DaySpec
{
    public int DaySpecId { get; set; }

    public DateTime Open { get; set; }

    public DateTime Close { get; set; }
}

public class WeekSpec
{
    public int WeekSpecId { get; set; }

    public bool booleanOne { get; set; }

    public DaySpec[] DaySpecs { get; set; }
}

public class ExceptionHoursSet
{
    public int ExceptionHoursSetId { get; set; }

    public int RepCount { get; set; }

    public int WeekSpecId { get; set; } // set which WeekSpec you are referencing below (for lazy-loading)

    public virtual WeekSpec HoursSet { get; set; }

    // etc . . .
}

public class Schedule
{
    public int ScheduleId { get; set; }

    public string Name { get; set; }

    public int WeekSpecId { get; set; } // set which WeekSpec you are referencing below (for lazy-loading)

    public virtual WeekSpec WeekSpec { get; set; }

    public IEnumerable<ExceptionHoursSet> ExceptionHoursSets { get; set; } 
}

I may have left a few properties out, but you get the idea (fill in where necessary). There are different ways you can approach this situation (lazy-loading, etc. . .), it is all really dependent on exactly what you need to do with the data.



来源:https://stackoverflow.com/questions/11614484/how-to-define-an-mvc-database-structure-using-the-same-sub-table-in-different-su

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