EF 4.0 Linq to Entity查询

时间:2011-05-15 13:19:08

标签: entity-framework-4 linq-to-entities

大家好我需要在Linq中复制这个SQL查询到实体

  select * from Subscriber a
  inner join User b on a.UserId = b.Id

  where b.Username = 'Name'

可能有人可能有所帮助。

1 个答案:

答案 0 :(得分:0)

试试这个:

var query = from s in context.Subscribers.Include("User")
            where s.User.Username == "Name"
            select s;

这假设Subscriber具有引用用户实例的导航属性User

如果您想使用join(不需要),可以将其用于内连接:

var query = from s in context.Subscribers
            join u in context.Users on s.User.Id equals u.Id
            where u.Username == "Name"
            select new 
                {
                    Subscriber = s, 
                    User = u
                };

或左外连接的这个:

var query = from s in context.Subscribers
            join u in context.Users on s.User.Id equals u.Id into x
            where u.Username == "Name"
            from y in x.DefaultIfEmpty()
            select new 
                {
                    Subscriber = s 
                    User = y,
                };