How to get all the birthdays of today?

后端 未结 5 1915
南方客
南方客 2021-01-23 09:21

Does anyone know how to make a Linq query that gets all the birthdays of today? The code below doesn\'t work :

var getBirthdays = 
    orgContext.CreateQuery<         


        
5条回答
  •  死守一世寂寞
    2021-01-23 10:05

    Anytime a vendor writes a four part blog series on how to do something as simple as finding a birthday (as Microsoft did in 2007), you have to know this won't be simple. So far as I can tell, this hasn't updated since then.

    • Find contacts with upcoming birthdays
    • Find contacts with upcoming birthdays - Part 2
    • Find contacts with upcoming birthdays - Parts 3 and 4

    So you have limited options:

    1. Make new fields called something like new_birthmonth and new_birthday that's updated every time a contact is created or updated via a plugin, and then query on those int fields.
    2. Using Dynamic Linq, construct an OR clause in your WHERE clause that checks to see if the birthday falls in a reasonable range of years (say, 140 for the long-livers) (code below).
    List birthdays = new List(); //will contain list of OR clauses
    
    //makes sure no CRM unsupported dates are passed (less than 1/1/1900)
    for (int i = Math.Min(140, DateTime.Today.Year - 1900); i > -1; i--) 
    {
        //adds a different date per year
        birthdays.Add
        (
            string.Format
            (
                //DateTimes are stored in UTC
                "BirthDate = DateTime.Parse(\"{0}\")",
                DateTime.Today.ToUniversalTime().AddYears(-i)
            )
        );
    }
    
    //completes the correct dynamic linq OR clause
    string birthdayList = string.Join(" OR ", birthdays);
    
    var getBirthdays = orgContext.CreateQuery()
        .Where(c => c.BirthDate != null)
        .Where(birthdayList)
        .ToList();
    

提交回复
热议问题