Home > Enterprise >  Iterate over Entity Framework object properties
Iterate over Entity Framework object properties

Time:08-04

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.

CodePudding user response:

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

CodePudding user response:

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 
  • Related