LINQ查询不会提取所需的所有记录

时间:2016-09-23 10:56:17

标签: c# linq nhibernate

我在使用LINQ查询时遇到了一些问题。

此查询根据存储库中的条目创建新对象列表。 这是原始查询:

var accounts = (from a in entityRepository.Queryable<Account>()
                from l in a.ExternalLogins 
                select new
                {
                    a.ID,
                    FullName = a.FirstName + " " + a.LastName,
                    Status = a.Status == AccountStatus.Closed ? Enums.Status.Inactive : Enums.Status.Active,
                    Login = new
                    {   
                        ConnectionID = l.Connection.ID,
                        l.Connection.ConnectionType,
                        l.Identity    
                    },
                    a.AdminAccess,
                    a.Username,
                    a.Email
                }).ToList();

我的问题是并非所有a都有a.ExternalLogins。由于语句from l in a.ExternalLogins中的附加内容,查询未提取这些帐户。我尝试将查询修改为:

 var accounts = (from a in entityRepository.Queryable<Account>() 
                 select new
                {
                    a.ID,
                    FullName = a.FirstName + " " + a.LastName,
                    Status = a.Status == AccountStatus.Closed ? Enums.Status.Inactive : Enums.Status.Active,
                    Login = (from l in a.ExternalLogins
                    select new
                    {   
                      ConnectionID = l.Connection.ID,
                      l.Connection.ConnectionType,
                      l.Identity    
                    }),
                    a.AdminAccess,
                    a.Username,
                    a.Email
                }).ToList();

但是我收到了'System.Reflection.AmbiguousMatchException'异常。 通过查找该异常,我猜测原因是因为AccountConnection都有字段ID

我是否朝着正确的方向前进?我是否要追查此异常,或者我的查询不正确?

如果这是微不足道,我道歉;我是LINQ查询的新手,我的谷歌技能在这一点上让我失望了!

1 个答案:

答案 0 :(得分:2)

要在Linq中执行左外连接,请添加DefaultIfEmpty()调用并在结果中检查null:

var accounts = (from a in entityRepository.Queryable<Account>()
            from l in a.ExternalLogins.DefaultIfEmpty() 
            select new
            {
                a.ID,
                FullName = a.FirstName + " " + a.LastName,
                Status = a.Status == AccountStatus.Closed ? Enums.Status.Inactive : Enums.Status.Active,
                Login = (l == null) ? null : new
                {   
                    ConnectionID = l.Connection.ID,
                    l.Connection.ConnectionType,
                    l.Identity    
                },
                a.AdminAccess,
                a.Username,
                a.Email
            }).ToList();