我正在尝试进行左连接,即1条用户记录与1条记录(如果有)联系在一起。运行此命令时,它仍然拉多个联系人,而忽略了我的条件“ where c.RecordType ==“ USR””。
public class Users
{
public int Id { get; set; }
... other properties
public Contact Contact { get; set; }
}
public class Contact
{
public int Id { get; set; }
public int RecordID { get; set; }
public string RecordType { get; set; }
[ForeignKey("RecordID")]
public Users User { get; set; }
}
Linq查询
var query3 = (from c in db1.Contacts
join u in db1.Users
on c.RecordID equals u.Id
into a
from b in a.DefaultIfEmpty(new Models.Users())
where c.RecordType == "USR"
&& b.Lastname.Contains(name)
&& b.Active == 1
select new
{
b.Id,
b.FirstName,
b.Lastname,
b.FullName,
b.Contact
}).ToList();
对我要去哪里的任何帮助将不胜感激。
谢谢, 亚当
答案 0 :(得分:1)
您可以在linq中进行联接,而无需使用join关键字。我对左联接使用以下构造,没有任何问题。
var query3 = (from c in db1.Contacts
from u in db1.Users.Where(x => c.RecordID == x.Id).DefaultIfEmpty()
where (c.RecordType == "USR")
&& u.Lastname.Contains(name) && (u.Active == 1)
select new
{
u.Id,
u.FirstName,
u.Lastname,
u.FullName,
u.Contact
}).ToList();
答案 1 :(得分:0)
根据相关信息
1条用户记录中有1条(如果有)与之关联的联系人记录
意味着一个用户可以有零个或多个联系人,因此您假设将User用作主要实体,然后在Contacts上保留联接。另外,您还应该在JOIN本身期间应用Contact类型过滤器,如下所示
var query3 = ( join u in db1.Users
from c in db1.Contacts
on new { Record = c.RecordID, Type = c.RecordType } equals new { Record = u.Id, Type = "USR"} into b
from cont in b.DefaultIfEmpty(new Models.Contacts())
where u.Lastname.Contains(name)
&& u.Active == 1
select new
{
u.Id,
u.FirstName,
u.Lastname,
u.FullName,
cont.Contact
}).ToList();