Week and day entities - c#

I am learning C# and MVC with ASP.NET. I am making an application that takes daily data and splits it up into weeks.
My question is: How should I go about making the entities? I want it so that you have a WeekNo and a DayNo and you use them to display, edit and create data and tables. So for example, WeekNo = 1 and DayNo = 1 would be Monday in week 1. WeekNo = 1 and DayNo = 2 would be Tuesday and so on.
I'm new to this and not very good at information management. Do I need foreign keys?
I was thinking:
public class Day
{
public int WeekNo { get; set; }
public int DayID { get; set; }
public int DayNo { get; set; }
public string DayofWeek { get; set; }
//then other declarations, not important
[ForeignKey("DayNo")]
}
public class Week
{
public int ID { get; set; }
public int WeekNo { get; set; }
public int DayofWeek { get; set; }
}
Does the foreign key go in Day or Week or do I even need it?

On the assumption that you meant Objects when saying entities.
Here is how you can structure an Object for use per day:
public class myDailyObject
{
public myDailyObject()
{ }
public int ObjectID { get; set; }
public int WeekNo { get; set; }
public int DayNo { get; set; }
public string DayofWeek { get; set; }
//Other variables can go here.
}
Otherwise, you can use the following structure for use per week:
public class myWeeklyObject
{
public myWeeklyObject()
{
DataByDay = new Dictionary<int, myDataObject>();
}
public int ObjectID { get; set; }
public int WeekNo { get; set; }
public Dictionary<int, myDataObject> DataByDay { get; set; }
}
public class myDataObject
{
//Other variables can go here.
}
In here, you can use the Dictionary<int, myDataObject> called DataByDay to contain an instance of the myDataObject Object for each day of the week.
Example of usage:
The Weekly object:
//Declare the weekly object:
myWeeklyObject thisWeek = new myWeeklyObject();
//Populate variables of thisWeek here:
thisWeek.ObjectID = thisWeek.WeekNo = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
//The line above gets the current weekNo for the year.
You could also fetch this object from somewhere if one already exists for this week.
So now, the daily object:
//Get the day of the week as an int:
int dayOfWeek = (int)DateTime.Now.DayOfWeek + 1; //DayOfWeek is 0 based
//Daclare object for a specific day:
myDataObject newObject = new myDataObject();
//Populate variables of newObject here.
//Then add it with the int dayOfWeek as the Key to the DataByDay Dictionary.
thisWeek.DataByDay.Add(dayOfWeek, newObject);
I hope this answers your question (and future questions such as how to get the WeekNo), or at least is of some kind of help.
Good luck.

Related

Iterate over Entity Framework object properties

I have a table "StaffMembers" that have columns indicating the number of days worked in a month, the properties in the model are as follows:
public class StaffMember
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Phone { get; set; }
public string Email { get; set; }
public string BirthDate { get; set; }
public int OctDays { get; set; }
public int NovDays { get; set; }
public int DecDays { get; set; }
public int JanDays { get; set; }
public int FebDays { get; set; }
public int MarDays { get; set; }
public int AprDays { get; set; }
}
now I retrieve the specific staffMember using linq:
var staffMember = (from b in db.StaffMembers
where b.Id == Id
select b).FirstOrDefault();
what I want to do is to loop over the months properties in staffMember and add all the worked days together to get total working days in the year.
for example if he worked 10 days in oct and 20 days in dec and 30 days in jan, I want a way to iterate over the months and sum the days.
You can do it by iterating over object properties and apply your condition on it.
static void Main(string[] args)
{
var staffA = new StaffMember();
int totalWorkDays = 0;
staffA.AprDays = 5;
staffA.FebDays = 7;
foreach (var item in staffA.GetType().GetProperties())
{
if (item.Name.EndsWith("Days"))
{
totalWorkDays += (int)item.GetValue(staffA)!;
}
}
Console.WriteLine(totalWorkDays);
}
this snippet prints ( 5 + 7 ) => 12
You can use reflection to iterate over the properties, but I do not recommend this because you have to point anyway which properties you want to take into consideration. That's because you have multiple integer properties like Id and Phone so you cannot indicate in the loop that you want to sum integer properties, you have to show explicitly that you want to sum OctDays etc. or write some algorithms that indicates that the current property is responsible for the month. So the best way (and in my opinion simplier than reflection way) would be just to get each of the month explicit and sum like this:
var sum = staffMember.OctDays + staffMember.NovDays + staffMember.DecDays + staffMember.JanDays + staffMember.FebDays + staffMember.MarDays + staffMember.AprDays

Entity Framework Adding Child Objects to DB

I am currently stuck on adding a new child entity to my database using lamda queries.
The structure of my database is that Area has a one to many relationship with
Shifts
In my seeding database I populate the Shifts while creating the Areas:
new Area()
{
AreaDesc = "Area 1",
AreaActive = true,
AreaCreatedDate = DateTime.Now,
SHFID = new Shift()
{
StartTime = new TimeSpan (5,30,00),
EndTime = new TimeSpan (11, 00, 00),
RequiredResources = 2,
ShiftDesc = "AM Shift",
ShiftDayID = 1
}
}
That works fine, where I am struggling and probably due to a simple lack of understanding on entity frameworks abilities is adding a new Shift to an existing Area.
So far I have the following
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).ToList();
var Shift = new Shift
{
Area = AreaVal,
StartTime = StartTime,
EndTime = EndTime,
ShiftDayID = model.ShiftDayID,
ShiftDesc = model.ShiftDesc
};
Thinking that once I had the correct Area (I have the ID coming from the model) I could load the Area and pass it as the Area parameter in the Shift and entity framework would know what to do.
The Error I get in the parser is:
Cannot implicitly convert type (Generic.List to
Models.Area.
I have also considered going from the other direction using _context.Areas.Update() but have been unable to work that one out very well.
Extra Info, Model Structures
Shift.cs
public class Shift
{
[Key]
public int SHFID { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public int RequiredResources { get; set; }
public string ShiftDesc { get; set; }
public int ShiftDayID { get; set; }
public DateTime ShiftExDateStart { get; set; }
public DateTime ShiftExDateEnd { get; set; }
public int ShiftExLevel { get; set; }
public TimeSpan ShiftExStartTime { get; set; }
public TimeSpan ShiftExEndTime { get; set; }
public Area Area { get; set; }
}
Area.cs
public class Area
{
[Key]
public int AreaID { get; set; }
public string AreaDesc { get; set; }
public Boolean AreaActive { get; set; }
public DateTime AreaCreatedDate { get; set; }
public List<Shift> SHFID { get; set; }
public Company Company { get; set;}
}
You are on the right track.
AreaVal needs to be a single entity (Area), not a list of entities (List<Area>). Then it should work as expected.
Change the line:
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).ToList();
to
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).Single();

Storing actual repeating date's without the year part

Using the Entity Framework data access model, I am attempting to store Clubs including their meeting day/time information. Instead of using a free text field for the user to write something on the lines of "We meet on a Wednesday 5-6 and Thursday 7-8" I instead wish to store the meeting day and times in a more meaningful format.
I have a Club model something along the lines of:
public class Club
{
public bool VisuallyImpairedWelcome { get; set; }
public string Explanation { get; set; }
public List<CalendarEntry> MeetingDays { get; set; }
public DateTime DateCreated { get; set; }
}
CalendarEntry model looks like:
public class CalendarEntry
{
public int CalendarEntryId { get; set; }
public int ClubId { get; set; }
public Days Day { get; set; }
public DateTime From { get; set; }
public DateTime To { get; set; }
public Intervals Interval { get; set; }
public List<ExceptionDays> ExceptionDays { get; set; }
public string AdditionalInfo { get; set; }
}
The problem im having is with the List<ExceptionDays>, my thinking here would be the user could set up their regular meeting days i.e:
Monday 17:00 - 18:30
Wednesday 17:30 - 18:30
Occurrence: Every Week
Except Yearly: 25th December 26th December
Something along these lines, the problem is I have no idea how I should construct my ExceptionDays class, something along the lines of (pseudo:)
public class ExceptionDays
{
int Day { get; set; }
int Month { get; set; }
}
But obviously the Day/Month combination must be possible, and the date is to be excluded as this will be a re-occurring date.
Firstly am I taking the right approach here, if so how can I construct a water tight ExceptionDays class?

searching a date list

I have a collection list which contains the following fields
Date1
Xvalue
Yvalue
I want to seach within this list against another date list. For every date in the second list I want to get records starting between this minimum date and the next date is which (30 minutes to the minium date).
foreach (var item in selectedDates.Where(x => x.Checked))
{
// item.minDate is my starting date
// I want all records between item.minDate and 30 minutes added to it)
var t = lf.ReplicateBlocks.FindAll(o=> o.minimumCompletionDate >= item.
}
**UPDATE**
public class ReplicateBlock
{
public int ReplicateId { get; set; }
public string AssayNumber { get; set; }
public DateTime InitiationDate { get; set; }
public DateTime InitiationTime { get; set; }
public DateTime minimumCompletionDate { get; set; }
public DateTime minimumCompletionTime { get; set; }
public string correctedCount { get; set; }
public string moduleName { get; set; }
public string exception { get; set; }
}
public class RunLogEntryDatesDisplay
{
public DateTime runDate { get; set; }
public String DateRange { get; set; }
public bool Checked { get; set; }
public string MinimumReplicateId { get; set; }
}
The final output I am looking for is a revised Replicate Block list. RunLogEntryDatesDisplay is a checkbox list posted from the view. In this list I look at the checked date which is runDate and starting from the first selection I add 30 minutes to it and find all records in ReplicateBlock List in between and the edges. I will do the same for every selected date in the checbox list and in the end will have a final/filtered ReplicateBlockLisr based on users selections(checked item).
You could loop through the dates and populate a result list:
List<ReplicateBlock> blocks = new List<ReplicateBlock>();
foreach (var item in selectedDates.Where(x => x.Checked))
{
var t = lf.ReplicateBlocks.Where(o=>
o.minimumCompletionDate >= item.minDate &&
o.minimumCompletionDate <= item.minDate.AddMinutes(30));
blocks.AddRange(t);
}
You could also do it in one query:
var query = from d in selectedDates
from o in lf.ReplicateBlocks
where d.Checked &&
o.minimumCompletionDate >= d.minDate &&
o.minimumCompletionDate <= d.minDate.AddMinutes(30))
select o;

ASP.NET MVC 3 Compare 2 Lists with Model Objects for duplicates

I am building an ASP.NET MVC 3 application, where I have on list of custom objects according to this model:
public class AbnAmroTransaction
{
public int TransactionId { get; set; }
public int AccountNumber { get; set; }
public string Currency { get; set; }
public int TransactionDate { get; set; }
public int InterestDate { get; set; }
public decimal StartBalance { get; set; }
public decimal EndBalance { get; set; }
public decimal Amount { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
}
I also have second list with slightly similar objects of custom object type "Transaction" (which I get from my SQL Server 2008 database using a DBML):
Transaction LinqToSql Object
int TransactionId
int ImportId
int CategoryId
DateTime DateTime
Nvarchar(MAX) Currency
Money Amount
Nvarchar(MAX) Description
I'm trying to create a 3rd list that contains all AbnAmroTransactions, where the AbnAmroTransaction.TransactionId is not in the Transactions list (TransactionId). How do I do this without having to loop through both lists, which seems like a very unefficient way to do it?
I have found this article:
http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.equals.aspx
But that only seems to apply to objects of the same type.
If you are using linq then look at Except.
var list1 = new List<int>() {1,2,3,4,5};
var list2 = new List<int>() {4,5,6,7};
var newList = list1.Except(list2);
New list will contain {4,5}
But you would have to any some check for transaction Id first.

Categories