【问题标题】:Upgrading to Entity Framework升级到实体框架
【发布时间】: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


【解决方案1】:

这将查询当前用户的文档,选择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

【讨论】:

  • 我认为这会起作用,但我应该添加什么“使用”?
  • 使用上下文作为新的上下文()
  • 对不起,我的意思是导入。当我实现您的代码时,它在 "Dim context as New Context()" 上给了我一个错误。当我使用智能感知时,它建议的任何导入都不能修复错误。
  • 我使用了以下导入语句:Imports System.Data.Entity。我将在我的答案中发布我的 Context 课程。
  • 好的,这应该可以。不幸的是,我暂时无法对其进行测试,因为我还有大约 170 个其他错误要修复,但我会回来确认!
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2011-07-28
  • 2012-03-12
  • 2011-12-12
  • 1970-01-01
相关资源
最近更新 更多