使用 EF,可以通过 GroupJoin 执行左外连接。有关联接的更多信息,请访问http://msdn.microsoft.com/en-us/library/bb896266.aspx。这是另一个可能有帮助的例子。http://msdn.microsoft.com/en-us/library/vstudio/bb397895.aspx。至于投影,可以使用匿名类型执行,例如
select new { Amount = 108, Message = "Hello" }
您的查询可能类似于
var query = from qf in context.QuizFamilies
join images in context.Images on qf.ImagesID = images.ID into quizImages
join imageData in context.ImageData on images.ImageDataID = imageData.ID into imgdata
from images in quizImages.DefaultIfEmpty()
from imageData in imgdata.DefaultIfEmpty()
select new { Id = qf.ID, Title = qf.Title, Uri = imageData.Uri};
更新
如果您想更改默认的 Get 实现,您可以简单地删除代码并更新方法签名。您不能返回匿名类型,因此如果您仍然只需要这 3 个字段,则需要一个额外的类。我个人会单独保留默认的 Get 方法并添加另一种方法
public class QuizFamilyTitleAndUri
{
public String Id {get; set;}
public String Title {get; set;}
public Uri ImageUri {get; set;}
}
public IEnumerable<QuizFamilyTitleAndUri> GetQuizFamilies()
{
return var query = from qf in db.QuizFamilies
join images in db.Images on qf.ImagesID = images.ID into quizImages
join imageData in db.ImageData on images.ImageDataID = imageData.ID into imgdata
from images in quizImages.DefaultIfEmpty()
from imageData in imgdata.DefaultIfEmpty()
select new QuizFamilyTitleAndUri() { Id = qf.ID, Title = qf.Title, ImageUri = imageData.Uri};
}