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

时间:2017-01-22 06:50:42

标签: sql entity-framework ef-code-first asp.net-mvc-viewmodel

我尝试使用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是我的viewmodel类,包含:

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"}
}

1 个答案:

答案 0 :(得分:1)

让我们使用命名参数进行查询(您称之为备用方式)。参考这些参数的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()