如何使用自定义相等性检查通过EF Core查询集合?

时间:2019-09-10 22:49:28

标签: c# .net-core ef-core-2.1

我有两个联接表:

用户>设备

一个用户可以通过FK user_ID加入许多设备。设备表具有主键ID。但是该设备还具有被认为是唯一的令牌。

我正在尝试选择没有令牌的用户:

IQueryable<User> users = DbContext.Users.Where(u => u.ID == _id && !u.Devices.Contains(device));

此处传递的device具有令牌,而Device模型具有EqualsGetHashCode覆盖仅测试令牌上的相等性的测试:

public bool Equals(Device comp)
{
  return comp.DeviceId.Equals(this.DeviceId);
}

因此,如果我先选择用户,然后在代码查询设备集合中,我可以检查该用户是否尚未关联该设备:

IQueryable<User> users = DbContext.Users.Where(u => u.ID == _id);

User user = users.First();

if (!user.Devices.Contains(device))
{
  ...Contains here has compared devices based only on device token        
}

但是EF Core构造了查询:

SELECT TOP(1) [u].[ID], ...{other user properties cut for brevity}
      FROM [Users] AS [u]
      WHERE ([u].[ID] = @__id_0) AND @__8__locals1_device_1_Id NOT IN (
          SELECT [d].[Id]
          FROM [Device] AS [d]
          WHERE [u].[ID] = [d].[User_ID]
      )

在我看来,这只能基于设备的ID属性测试是否相等...

有什么方法可以构建与代码Equality / GetHashCode检查匹配的EF Core查询,还是必须在代码中执行此操作?

1 个答案:

答案 0 :(得分:0)

我转载了你的案子。请在下面找到代码。并查看注释以获取解释。

Set s = thisworkbook.Sheets("Data")
With s
    For j = 1 To finalcolumn Step 6
        For i = 2 To finalrow
            uniqueId = .Cells(i, 2 + j - 1).Value

            Set rngSearch = .Range(.Cells(i, j), .Cells(i, j+5))

            Set rngFound = rngSearch.Find(What:=uniqueId, LookIn:=xlValues, LookAt:=xlWhole)
                If rngFound Is Nothing Then
                    .Range(.Cells(i, 1 + j - 1), .Cells(i, 6 + j - 1)).Copy
                    Sheets("DataValidation").Range("A1048575").End(xlUp). _
                                   offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
                End If
        Next i
    Next j
End with