【发布时间】:2016-06-01 14:13:04
【问题描述】:
我正在尝试将 id 恢复到用户在我的程序中创建的最后一个文档。最初的 SQL 工作不是我自己的,但我的任务是升级到 EF。下面的代码 sn-ps。只需要知道如何更改语法,以便改用 EF 即可。 (使用VB.Net)
'query for the max item created by the user
SqlString = "SELECT max(IdDocuments) as MaxId FROM Documents WHERE ModifiedBy='" + Environment.UserName.ToLower + "' ;"
SqlDataAdapter = New SqlDataAdapter(SqlString, SqlConnectionString)
TableNow = New DataTable
SqlDataAdapter.Fill(TableNow)
SqlDataAdapter.SelectCommand.Connection.Close()`
我已经尝试过的:
DocNow = (From a In Db.Documents Where a.ModifiedBy = Environment.UserName.ToLower)
与 DB 的连接定义为:
'query the database
Dim IdNow As Integer = DocumentId
Dim DocNow As IEnumerable(Of Documents) = (From a In Db.Documents Where a.IdDocuments = IdNow).ToList
这是 bwyn 帮助后的当前代码(包括 SQL):
'if is new, get the last document for this user
If IsNew Then
'query for the max item created by the user
'SqlString = "SELECT max(IdDocuments) as MaxId FROM Documents WHERE ModifiedBy='" + Environment.UserName.ToLower + "' ;"
'SqlDataAdapter = New SqlDataAdapter(SqlString, SqlConnectionString)
'TableNow = New DataTable
'SqlDataAdapter.Fill(TableNow)
'SqlDataAdapter.SelectCommand.Connection.Close()
Dim context As New Context()
Dim lastId As Integer
Dim currentUser As String = Environment.UserName.ToLower()
lastId = context.Documents.Where(Function(doc) doc.ModifiedBy = currentUser).Select(Function(doc) doc.IdDocuments).Max()
'set to the document id
DocumentId = lastId
End If
【问题讨论】:
-
1) 由于 SQL 通常不区分大小写,因此您不需要调用
ToLower。 2)这段代码有什么问题吗? -
目前此代码无法正常工作,但我已将大部分代码重新格式化为不使用数据表和行,而是使用 ienumerables。
标签: vb.net entity-framework entity-framework-6