开发者

How to access associations in a LINQ query?

How to access associations in a LINQ query?

I'm having problems quering this (I am new to LINQ, please forgive me) and I have spent hours trawling the web. 开发者_开发百科In SQL I just want to do this

SELECT c.Forname, c.Surname cg.Title, g.GroupName
FROM Contact c
    inner join ContactGroup cg on cg.ContactID = c.ID
    inner join Group g on cg.GroupNameID = g.ID
WHERE g.ID=1;

I have attempted it but failed miserably as :

var result = 
    from c in cc.Contacts
    from cg in c.ContactGroups
    from g in cg.Group 
    where g.ID==1
    select new
    {
        c.Forename,
        c.Surname,
        cg.Title,
        g.GroupName
    };

Can someone please show me what I am doing wrong or direct me to somewhere with further information?

Much thanks.


I would switch things around a bit and start your query using the ContactGroup table. That way you have 'access' to all 3 tables.

from c in cc.ContactGroups
where c.GroupNameID == 1
select new {
    c.Contact.Forename,
    c.Contact.Surname, 
    c.Title,
    c.Group.GroupName
}

Here's the SQL produced in Linqpad (using Linq to Sql but EF wouldn't be too different) - it's almost exactly like your query.

-- Region Parameters
DECLARE @p0 Int = 1
-- EndRegion
SELECT [t1].[Forename], [t1].[Surname], [t0].[Title], [t2].[GroupName]
FROM [ContactGroups] AS [t0]
INNER JOIN [Contacts] AS [t1] ON [t1].[ID] = [t0].[ContactID]
INNER JOIN [Groups] AS [t2] ON [t2].[ID] = [t0].[GroupNameID]
WHERE [t0].[GroupNameID] = @p0


in linq your join looks like this

from c in cc.Contacts
join cg in c.ContactGroups on cg.Id equals c.Id

look here: http://www.dotnetperls.com/join


I personally found LINQPad to be a good resource on learning both LINQ in general and LINQ-to-SQL. Maybe it will help you.


Start here: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜