开发者

LINQ to Entities Join on DateTime.DayOfWeek

开发者 https://www.devze.com 2023-01-12 17:54 出处:网络
Imagine two tables: Shifts, RANK_S_DAY.Shifts contains a ShiftDate column which is DateTime and RANK_S_DAY has a DayOfWeek column.I need to join (int)ShiftDate.DayOfWeek equals DayOfWeek.I understand

Imagine two tables: Shifts, RANK_S_DAY. Shifts contains a ShiftDate column which is DateTime and RANK_S_DAY has a DayOfWeek column. I need to join (int)ShiftDate.DayOfWeek equals DayOfWeek. I understand why it won't work, but I'm not quite sure how I can change it. The Exception is:

The specified type member 'DayOfWeek' is not suppo开发者_高级运维rted in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

As I understand it, LINQ can't translate (int)ShiftDate.DayOfWeek to something SQL understands, Any ideas?

Here is the code:

Shifts = from s in en.Shifts
join j in en.RANK_S_JOB on s.kronos_JobPositions.JobID equals j.JOBNO
join d in en.RANK_S_DAY on (int)s.ShiftDate.DayOFWeek equals d.DAY_OF_WEEK
orderby
 d.RANK,
 j.RANK ascending
select s;


LINQ to SQL

var dayOfWeekCondition = (dt => dt.DayOfWeek == dayOfWeek);

LINQ to Entities

int dow = (int)dayOfWeek + 1; // SQL Day of week
var dayOfWeekCondition = (dt => SqlFunctions.DatePart(“weekday”, dt) == dow);

Source:

http://blog.abodit.com/2009/07/entity-framework-in-net-4-0/


It appears there isn't anything I can do at this level. So what I've done is created a stored proc that joins the two tables and imported it into the Entity, created a function import that returned a Shifts entity. Not sure if thats the best approach, but it works and is clean.


using System.Data.Objects.SqlClient; //Don't forget this!!

//You can access to SQL DatePart function using something like this:

YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL

//You can compare to SQL DatePart function using something like this:

DateTime dateToCompare = DateTime.Today;
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL


Interestingly, this works fine in Linq-to-Sql:

from o in Orders
join c in Categories on (int) o.OrderDate.Value.DayOfWeek equals c.CategoryID
where o.OrderDate != null
select c

That query is meaningless -- It's just some random joins with the proper datatypes. (I was using Northwind)

0

精彩评论

暂无评论...
验证码 换一张
取 消