升级到实体框架

时间:2016-06-01 14:13:04

标签: vb.net entity-framework entity-framework-6

我正在尝试将id恢复到我的程序中用户创建的最后一个文档。最初的SQL工作不是我自己的,但我的任务是升级到EF。代码片段如下。只需要知道如何更改语法,以便使用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 个答案:

答案 0 :(得分:0)

这将查询当前用户的文档,选择ID,然后返回最大ID:

    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.Id).Max()

编辑:我的上下文类

Public Class Context
    Inherits DbContext

    Public Property Documents As DbSet(Of Document)

End Class