我正在寻找以下linq查询和扩展方法的帮助:
DateTime? ddStartOfTime = Convert.ToDateTime("2016/04/10 11:15:00");
DateTime? ddEndOfTime = Convert.ToDateTime("2017/06/25 13:15:00");
List<int> doWeeksNeeded = new List<int>();
doWeeksNeeded.Add(201614);
doWeeksNeeded.Add(201616);
var dq1 = (from c in tblschedulefulldates
where doWeeksNeeded.Contains(c.ddJobStart.GetYearWeekFormat())
orderby c.diEmployeeID
select new
{
diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
});
以下是扩展方法:
public static int GetYearWeekFormat(this DateTime pddate)
{
int weekNo = GetIso8601WeekOfYear(pddate);
int year = pddate.Year;
if (weekNo == 1 && pddate.Month > 1) year = year + 1;
return Convert.ToInt32(year.ToString() + weekNo.ToString().Trim());
}
public static int GetIso8601WeekOfYear(this DateTime pddate)
{
System.Globalization.Calendar cal = System.Globalization.CultureInfo.InvariantCulture.Calendar;
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
System.DayOfWeek day = cal.GetDayOfWeek(pddate);
if (day >= System.DayOfWeek.Monday && day <= System.DayOfWeek.Wednesday)
{
pddate = pddate.AddDays(3);
}
// Return the week of our adjusted day
return cal.GetWeekOfYear(pddate, System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
}
然而,当我跑步时,我得到:
Method 'Int32 GetYearWeekFormat(System.DateTime)' has no supported translation to SQL
所以我决定创建另一个名为In:
的扩展public static bool In<T>(this DateTime value, IEnumerable<Int32> values)
{
if (values == null)
throw new ArgumentNullException("values");
int lnWeek = GetYearWeekFormat(value);
return values.Contains(lnWeek);
}
并称之为:
var dq1 = (from c in tblschedulefulldates
where c.ddJobStart.In(doWeeksNeeded)
orderby c.diEmployeeID
select new
{
diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
});
除了我不能让这个工作。它给出了以下错误:
The type arguments for method 'DateTimeExtensions.In<T>(DateTime, IEnumerable<int>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
有人可以帮忙吗?
答案 0 :(得分:1)
LINQ 2 SQL不知道如何将GetYearWeekFormat
翻译成SQL。
您需要先查询数据库,然后在本地列表上进行工作。
var localList = (from c in tblschedulefulldates
select new
{
ddJobStart= c.ddJobStart,
diEmployeeID= c.diEmployeeID,
}).ToList();
var dq1 = (from c in localList
where doWeeksNeeded.Contains(c.ddJobStart.GetYearWeekFormat())
orderby c.diEmployeeID
select new
{
diEmployeeID = c.diEmployeeID == null ? 0 : (int)c.diEmployeeID,
dnDayOfWeek = c.ddJobStart.DayOfWeek == null ? 0 : (int)c.ddJobStart.DayOfWeek
});