我正在尝试编写一个LINQ
查询,该查询将在SQL
之后呈现。我已经接近了,但仍然不正确。
所需的SQL
SELECT
TableDisplayColumns.Id
, TableDisplayColumns.ViewName
, TableDisplayColumns.ColumnName
, TableDisplayColumns.ControllerName
, TableDisplayColumns.TableDisplayName
, TableDisplayColumns.IsVisibleByDefault
FROM dbo.TableDisplayColumns
LEFT JOIN dbo.UserTableDisplayColumns ON UserTableDisplayColumns.TableDisplayColumnId = TableDisplayColumns.Id
WHERE
(
(TableDisplayColumns.IsVisibleByDefault = 1 AND UserTableDisplayColumns.IsNotVisible IS NULL)
OR UserTableDisplayColumns.IsNotVisible = 0
)
AND (TableDisplayColumns.ControllerName = 'Contacts' AND TableDisplayColumns.ViewName = 'Index')
当前SQL
DECLARE @p0 NVarChar(1000) = 'Index'
DECLARE @p1 NVarChar(1000) = 'Contacts'
-- EndRegion
SELECT [t0].[Id], [t0].[ColumnName], [t0].[IsVisibleByDefault], [t0].[TableDisplayName], [t0].[ViewName]
FROM [TableDisplayColumns] AS [t0]
LEFT OUTER JOIN ([UserTableDisplayColumns] AS [t1]
LEFT OUTER JOIN [TableDisplayColumns] AS [t2] ON [t2].[Id] = [t1].[TableDisplayColumnId]) ON [t0].[Id] = [t1].[TableDisplayColumnId]
WHERE ([t0].[ViewName] = @p0) AND ([t0].[ControllerName] = @p1) AND ([t0].[IsVisibleByDefault] = 1) AND ([t2].[IsVisibleByDefault] = 1)
实体
public class UserTableDisplayColumn
{
public int Id { get; set; }
public int TableDisplayColumnId { get; set; }
public bool IsNotVisible { get; set; }
public virtual TableDisplayColumn TableDisplayColumn { get; set; }
}
public class TableDisplayColumn
{
public int Id { get; set; }
[StringLength(50), Required]
public string ViewName { get; set; }
[StringLength(50), Required]
public string ColumnName { get; set; }
[StringLength(50), Required]
public string ControllerName { get; set; }
[StringLength(50), Required]
public string TableDisplayName { get; set; }
[Required]
public bool IsVisibleByDefault { get; set; }
}
最后是当前查询:
var query =
(
from column in Context.TableDisplayColumns
.Where(x=>x.IsVisibleByDefault)
.Where(x=>x.ControllerName == "Contacts")
.Where(x=>x.ViewName == "Index")
join userColumn in Context.UserTableDisplayColumns on column.Id equals userColumn.TableDisplayColumnId into userColumnColumns
from userColumnColumn in userColumnColumns.DefaultIfEmpty()
select new TableDisplayColumn()
{
Id = column.Id,
ColumnName = column.ColumnName,
ControllerName = column.ColumnName,
IsVisibleByDefault = column.IsVisibleByDefault,
TableDisplayName = column.TableDisplayName,
ViewName = column.ViewName
}
).ToList();
如果UsersColumns
表中没有任何内容,我要完成的工作将获得默认列。如果UsersColumns
中有记录,那么我只想在IsNotVisible
= false时返回。
答案 0 :(得分:0)
您可以使用let
关键字以左连接方式引入集合。
var query =
from x in Context.TableDisplayColumns
where x.ControllerName == "Contacts"
where x.ViewName == "Index"
let ys = Context.UserTableDisplayColumns.Where(y => y.TableDisplayColumnId == x.Id)
where (x.IsVisibleByDefault && !ys.Any()) || ys.Any(y => y.IsNotVisible == 0)
select x;