按相关数据

时间:2015-10-02 20:10:27

标签: c# asp.net-mvc entity-framework linq

我使用的是MVC5 EF6和Identity 2.1。

我有两个班级:

    public class Incident 
        {
           public int IncidentId {get; set;}
           ...//Title, Description, etc
           public virtual ICollection<FollowedIncident> FollowedIncidents { get; set; }
           public virtual ApplicationUser User { get; set; }
        }

        public class FollowedIncident
        {
           public int FollowedIncidentId { get; set; }
           public string UserId { get; set; }
           public int IncidentId { get; set; }

           public virtual Incident Incident { get; set; }
           public virtual ApplicationUser User { get; set; }
        }

因此,用户将能够跟踪事件。 (首先,我不完全确定我是否需要ICollection和公共虚拟关系引用,但暂时添加它们。)

我尝试创建查询,向用户显示其关注事件的结果。在我的控制器中,我的查询就像这样开始(我使用Troy Goode的分页包...即listUnpaged):

IQueryable<Incident> listUnpaged = db.Incidents.OrderByDescending(d => d.IncidentDate);

然后我想通过跟踪事件进行过滤。所以,我想显示userId(参数I传递给它)等于FollowedIncident中的UserId的事件。我试过这样的(关于从IEnumerable转换为bool的错误):

listUnpaged = listUnpaged.Where(s => s.FollowedIncidents.Where(t => t.UserId == userId));

这个(没有错误,但根本没有过滤):

listUnpaged = listUnpaged.Where(s => s.FollowedIncidents.All(t => t.UserId == userId));

对我而言,它似乎应该像这样简单:

listUnpaged = listUnpaged.Where(s => s.FollowedIncidents.UserId == userId));

但是,linq扩展似乎不喜欢相关的数据子属性? (我为我的编程术语道歉,因为我还没有将所有名称拼凑在一起。)

任何人都知道如何做到这一点?看来我甚至可能没想到它是正确的? (...因为在过去,我总是使用相关数据来补充或添加结果的属性。这将是我第一次想要通过相关数据缩小结果。)

谢谢。

1 个答案:

答案 0 :(得分:0)

实际上你正在以错误的方式获取事件..因为事件是FollowedIncident的导航属性你应该只使用

IQueryable<Incident> listUnpaged = db.FollowedIncidents
                                     .Where(a => a.UserId == userid)
                                     .Select(a => a.Incident)
                                     .OrderByDescending(d => d.IncidentDate);

另一种选择是使用Any()

IQueryable<Incident> listUnpaged = db.Incidents
                                 .Where(a => a.FollowedIncidents.Any(b => b.UserId == userid)
                                 .OrderByDescending(d => d.IncidentDate);

就像说

Select * 
From Incidents
Where Id IN (Select IncidentId
             From FollowedIncident 
             Where UserId = @UserId)
相关问题