What I Trying to achieve:
When a user enters a line into a table (EntryLine), they enter a description and a date. Now in C# under the inserting code of EntryLine, I can use this code:
partial void EntryLine_Inserting(EntryLine entity)
{
if (entity.Day == null)
{
DateTime getDay = Convert.ToDateTime(entity.EntryDate);
entity.Day = getDay.ToString("dddd");
//entity.Day = getDate
}
}
Now what this code does above is takes the date entered by the user and just adds the day into the database using the .ToString method (i.e. Wednesday)
in the long run this will be inefficient so is there a way of associating that day (Wednesday) with a matching field in the Day table? and also then assign it to the correct ID? I would be doing this by using the below ERD:
DayName ID
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
Friday 5
Saturday 6
Sunday 7
One option would be to use the DayOfWeek property as follows: -
partial void EntryLines_Inserting(EntryLine entity)
{
entity.Day = Days_SingleOrDefault((int)entity.EntryDate.DayOfWeek);
}
This requires that the IDs in your Day table mirror the following DayOfWeek enumeration values: -
DayName ID
Sunday 0
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
Friday 5
Saturday 6
Alternatively, you could use the approach below, which is based on identifying the matching DayName in your Day table: -
partial void EntryLines_Inserting(EntryLine entity)
{
var dow = entity.EntryDate.DayOfWeek.ToString();
entity.Day = Days.Where(d => d.DayName == dow).SingleOrDefault();
}