我正在尝试为我的上下文创建一个“AssociateWith”数据加载选项,以过滤当前用户有权访问的行。我的简单数据模型是这样的:
表格
UserPermissions
PK:ID
FK:RelatedUserID可以为空的
FK:RelatedItemID不可为空
用户
PK:ID
产品
PK:ID
FK:RelatedCategoryID不可为空
分类 PK:ID
在我的datacontext上,我正在尝试做类似的事情:
//dbContext is my LINQ context
//current_user_id is the id of my current logged in user
var dlo = new DataLoadOptions();
//issue->UsersPermissions is one->many relationship
// if I omit this LoadWith line, no associatewith filter
// is created in the generated sql code
dlo.LoadWith<Items>(i=>i.UserPermissions);
dlo.AssociateWith<Items>(i=>
i.UserPermissions.Where(p=>
p.RelatedUserID.HasValue && p.RelatedUserID.Value == current_users_id));
dbContext.LoadOptions = dlo;
对我来说,一切似乎都是合理的,但在SQL中生成的查询如下所示:
SELECT [t0].[ID], [t1].[ID] AS [ID2], [t1].[RelatedUserID], [t1].[RelatedItemID]
(SELECT COUNT(*)
FROM [dbo].[UserPermissions] AS [t2]
WHERE (([t2].[RelatedUserID] = @p0)) AND ([t2].[RelatedItemID] = [t0].[ID])
) AS [value]
FROM [dbo].[Items] AS [t0]
LEFT OUTER JOIN [dbo].[UserPermissions] AS [t1] ON ([t1].[RelatedUserID] = @p0)
AND
([t1].[RelatedItemID] = [t0].[ID])
ORDER BY [t0].[ID], [t1].[ID]
如何强制INNER JOIN而不是LEFT OUTER JOIN?我是否在后端错误地模拟了我的关系?
感谢您的帮助。
MMAS
答案 0 :(得分:1)
LINQ to SQL生成LEFT OUTER JOIN只是因为UserPermissions.RelatedUserID
列可以为空。底层的LINQ提供程序不够“智能”,无法进一步优化该查询到简单的INNER JOIN。我认为你无法做到这一点。