我正在尝试获取客户端记录列表以及每个实体的最新ClientNote记录。如果客户端没有关联的注释,我希望ClientNote对于该客户端为空(类似于TSQL中的LEFT JOIN)。
我有两个相似的表,如:
CREATE TABLE [dbo].[Client](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ClientNumber] [varchar](10) NOT NULL,
[Name] [varchar](100) NOT NULL,
[AssociateName] [varchar](30) NOT NULL,
[AssignedToID] [int] NULL,
[District] [varchar](6) NOT NULL,
[RegionID] [int] NOT NULL,
[CreateDate] [datetime] NOT NULL,
)
CREATE TABLE [dbo].[ClientNote](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ClientID] [int] NOT NULL,
[Note] [varchar](4000) NOT NULL,
[NoteDate] [datetime] NULL,
[TicklerDate] [datetime] NULL,
[EnteredByAgentID] [int] NOT NULL,
[CreateDate] [datetime] NOT NULL,
)
我需要一个EF左外连接来返回客户端和最新的ClientNote Client.Name喜欢'%ike%' AND(要么没有ClientNote,要么ClientNote CreateDate超过60天)。 所以,我想为每个匹配返回两个对象:一个Client和一个可选(null)ClientNote 我尝试了很多东西,而我却没有得到我所寻求的结果。
答案 0 :(得分:0)
尝试类似下面的内容,您也可以将最后一个从SingleOrDefault()更改为FirstOrDefault()或者可能更改为数组:
var clientInfo = (from a in yourdatacontext.Client
join b in yourdatacontext.ClientNote on a.ID equals b.ID into temp
from t in temp.DefaultIfEmpty() //this is what does the left outer join
where a.Name.Contains("ike") && b.CreateDate > DateTime.Now.AddDays(60)
select new {
a,
t
}).SingleOrDefault(); //or change to .ToArray();
foreach (var client in clientInfo)
{
var client.a.t.yourfieldname;
//or
var client.a.yourfieldname;
}