使用 EF 代码优先的原始 SQL 查询不起作用

Raw SQL queries with EF code-first doesn't work

我正在尝试使用 SQL JOINWHERE 子句显示 2 个表中的值(EF 代码优先)。

Dim query = db.pt.SqlQuery("SELECT p.id, p.name, p.dob, pv.visitId, pv.vDate
                             FROM pt p 
                             JOIN pt_v pv ON p.id = pv.id
                             WHERE p.id like @p0 OR p.name like @p1", str1, str2).ToList()

我试过替代方法。下面是代码:

Dim id = New SqlParameter("@id", str1)
Dim name = New SqlParameter("@name", str2)
Dim query As String = "select p.id id, p.name name, p.dob dob, pv.visitId visitId, pv.vDate vDate
                       from pt p 
                       join pt_v pv on p.id = pv.id
                       where p.id like @id or p.name like @name"

Dim Result = db.Database.SqlQuery(Of PtLookupVM)(query, id, name).ToList()

PtLookupVM 是我的视图模型 class,它有这些:

Public Property id As String
Public Property name As String
Public Property dob As String
Public Property visitId As String
Public Property vDate As String

但是两者的输出结果都是零行。

这是示例数据:

Dim p As New List(Of pt) From {
        New pt() With {.id = 1, .name = "siti", .dob = "2011-11-17"},
        New pt() With {.id = 2, .name = "siti nur", .dob = "2011-12-17"}
}

Dim pv As New List(Of pt_v) From {
        New pt_v() With {.visitId = 1, .id = 1, .vDate = "2016-01-17"},
        New pt_v() With {.visitId = 2, .id = 1, .vDate = "2016-05-17"},
        New pt_v() With {.visitId = 3, .id = 2, .vDate = "2016-07-17"}
}


Dim pList As New List(Of PtLookupVM) From {
        New PtLookupVM() With {.id = 1, .name = "siti", .dob = "2011-11-17", .visitId = 1, .vDate = "2016-01-17"},
        New PtLookupVM() With {.id = 1, .name = "siti", .dob = "2011-11-17", .visitId = 2, .vDate = "2016-05-17"},
        New PtLookupVM() With {.id = 2, .name = "siti nur", .dob = "2011-12-17", .visitId = 3, .vDate = "2016-07-17"}
    }

我想要得到的实际上是一个名为 "siti" 的人的列表。但我不想要多余的值。所以它应该只显示如下值:

这是我的预期输出:

Dim pList As New List(Of PtLookupVM) From {
        New PtLookupVM() With {.id = 1, .name = "siti", .dob = "2011-11-17", .visitId = 1, .vDate = "2016-01-17"},
        New PtLookupVM() With {.id = 2, .name = "siti nur", .dob = "2011-12-17", .visitId = 3, .vDate = "2016-07-17"}
}

让我们使用命名参数进行查询(您称之为替代方式)。在引用这些参数的 WHERE 子句中使用的标准是

p.id like @id

p.name like @name

如您所见,没有使用占位符,因此如果您不通过参数提供它们,LIKE 将简单地用作 =,因此不会匹配您的内容例如 str2 包含 "sity".

要匹配字符串而不考虑目标字段中的位置,您应该用“%”将用户值括起来:

Dim id = New SqlParameter("@id", "%" & str1 & "%")
Dim name = New SqlParameter("@name", "%" & str2 & "%")

或者如果您更喜欢带有隐式参数的第一个变体:

Dim query = db.pt.SqlQuery("SELECT p.id, p.name, p.dob, pv.visitId, pv.vDate
                             FROM pt p 
                             JOIN pt_v pv ON p.id = pv.id
                             WHERE p.id like @p0 OR p.name like @p1", "%" & str1 & "%", "%" & str2 & "%").ToList()