I got a huge LINQ-statement with multiple joins with multiple conditions. I need to use database functions (DatePart, DiffDays) in one of the joins. I use Moq for Unit Testing. As those DBFunctions are only invokable via static methods I can't mock these methods. If I call them via SqlFunctions or EntityFunctions I get a NotSupportedException ("This function can only be invoked from LINQ to Entities."), but my application works. If I use System.Data.Entity.DbFunction it also works in my application, but not in my unit-test.
I shortened the LINQ-Statement, actually it contains a lot more joins:
var resultQuery = from t1 in ctx.Table1.AsNoTracking()
join t2 in ctx.Table2 on new
{
//works for application, but not in Unit-Test, firstMonday is a predefined DateTime-variable
z3 = (int)EntityFunctions.DiffDays(firstMonday, t1.Date)%7,
//works only in Application, but not in Unit-Test
z4 = SqlFunctions.DatePart("wk", t2.Date)
} equals new
{
z3 = (int)t2.Day,
z4 = SqlFunctions.DatePart("wk", t2.BeginDate)
} into tGroup
from x in tGroup.DefaultIfEmpty()
where
[...]
//Class DataTransferObjekt defined to hold attributes of both tables
select new DataTransferObject
{
Id = t1.Id,
Date = t1.Date,
[...]
T2Id = t2.ID
};
I tried a lot and did a lot research. Best approaches I found here: EntityFunctions.TruncateTime and unit tests
But I was unable to transfer the offered solutions to my special case as my condition is part of a join and the solution using System.Data.Entity.DbFunction offered in the second answer also didn't work for the Unit-Test as mentioned before.
Any help would be appreciated, I'm still quite new in Moq and LINQ also!