【问题标题】:Join a table with bridge table and get data from main table and if data exists in bridge table then get it as well使用桥表加入表并从主表中获取数据,如果桥表中存在数据,则也获取它
【发布时间】:2019-05-02 05:25:38
【问题描述】:

我有两个表“Event(EventId,EventName,....,UpdatedBy)”、“User(UserId,Username...)”和一个桥表“EventAttendee(EventId,UserId)”

from c in context.Events
from u in c.users 
where c.EventId == eventId
select s

上面是做一个内部连接,所以如果 EventAttendee 表中没有记录,那么我没有得到任何记录。

我希望始终从 Event 表中获取事件详细信息,如果 EventAttendee 表中有该事件的任何记录,则获取 UserId 和 Username。由于我的实体模式不显示桥接表,如何在 linq to sql 中使用实体框架执行此操作?

【问题讨论】:

标签: c# entity-framework linq-to-sql


【解决方案1】:

只需添加DefaultIfEmpty():

from e in context.Events
from u in e.users.DefaultIfEmpty()
where e.EventId == eventId
select ...

不确定sselect 中是什么,但可能类似于

select new { e.EventName, UserId = (int?)u.UserId, u.UserName }

这将为您提供包含所有参加者的活动列表,或者在没有参加者时为您提供与用户相关的数据的null

【讨论】:

  • c.users 表不为空,因此无济于事。
  • @NetMage c.users 是事件的用户集合。范围变量名称有点混乱。重命名它们。
  • @GertArnold 如果我在列表中选择用户 ID 和用户名(例如:select new { e.EventName, EventAttendees = new List{new EventAttedee {UserId = (int?)u.UserId, UserName = u.UserName}}}),这实际上是返回带有 1 个用户 ID 为空且用户名为空字符串的项目的 EventAttendees。我该如何过滤这个?
  • 你要过滤什么?
  • @GertArnold 如果用户 ID 为空,我不想在列表中插入项目
猜你喜欢
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 2016-02-20
  • 2016-01-17
  • 1970-01-01
相关资源
最近更新 更多