EntityFunctions.TruncateTime and unit tests

后端 未结 6 1591
悲&欢浪女
悲&欢浪女 2020-12-14 15:57

I\'m using System.Data.Objects.EntityFunctions.TruncateTime method to get date part of a datetime in my query:

if (searchOptions.Date.HasValue)
         


        
6条回答
  •  粉色の甜心
    2020-12-14 16:34

    Although I like the answer given by Smaula using the EntityExpressions class, I think it does a bit too much. Basically, it throws the entire entity at the method, does the compare, and returns a bool.

    In my case, I needed this EntityFunctions.TruncateTime() to do a group by, so I had no date to compare to, or bool to return, I just wanted to get the right implementation to get the date part. So I wrote:

    private static Expression> GetSupportedDatepartMethod(DateTime date, bool isLinqToEntities)
        {
            if (isLinqToEntities)
            {
                // Normal context
                return () => EntityFunctions.TruncateTime(date);
            }
            else
            {
                // Test context
                return () => date.Date;
            }
        } 
    

    In my case, I did not need the interface with the two seperate implementations, but that should work just the same.

    I wanted to share this, because it does the smallest thing possible. It only selects the right method to get the date part.

提交回复
热议问题