LINQ self join in ASP.NET MVC3
I have a situation where I need to do a self join on a table in LINQ. The table consists of fields ItemsID, Title, SeriesTitle, and many other. An item can be either a series or members and I can tell that by looking into ItemId which has "S" or "M" letters on it. I need to retrieve all records that are member of a series with ItemId "S117". I can do this in simple SQL by the code below,
select i.Series_Title, i.Item_ID, i2.Item_ID as Member_ID,
i2.开发者_如何学JAVATitle as Member_Title, i2.Series_Title as Member_Series_Title
from Items i join Items i2 on i.Series_Title = i2.Series_Title
where i.Item_ID = "S117"
Now, I translated this query in LINQ which goes as
items = _dataContext.Items.AsQueryable();
items = from series in items
join members in items on series.Series_Title.ToLower()
equals members.Series_Title.ToLower()
where series.Item_ID.ToLower().Equals(itemId)
select series;
The last line of this query select series
will only retrieve series but not members and I need members also.
I am using MVC3 Razor view where I have to display almost all fields so I am not using select new {....}
Even when I tried to use select new {series, members}
, I got this exception -
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.LinQ.IQueryable<My.App.models.Items>' An explicit conversion exist.
Any suggestions would be highly appreciated.
Try this:
var items1 = _dataContext.Items.AsQueryable();
var items2 = from series in items1
join members in items1 on series.Series_Title
equals members.Series_Title
where series.Item_ID== 'S117'
select series;
精彩评论