2016-06-01 8 views
2

私のプログラム内のユーザーによって作成された最後のドキュメントにIDを回復しようとしています。オリジナルのSQLの仕事は私のものではありませんが、私はEFにアップグレードすることを任されています。以下のコードスニペット。代わりにEFを使用するように構文を変更する方法を知る必要があります。私はすでに試してみました何Entity Frameworkへのアップグレード

'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()` 

(VB.Net使用):として定義DBへ

DocNow = (From a In Db.Documents Where a.ModifiedBy = Environment.UserName.ToLower) 

接続:

'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 
+0

1)一般的なSQLには、大文字と小文字が区別されていないので、あなたはshouldn ToLowerに電話する必要はありません。 2)このコードに問題はありますか? –

+0

このコードは現在のところ動作しませんが、データテーブルや行を使用しない代わりに、ほとんどのコードを再フォーマットして、代わりにienumerablesを使用しています。 – MattCucco

+0

http://stackoverflow.com/questions/157786/how-do-i-get-the-max-row-with-a-group-by-in-linq-query –

答えて

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 
+0

私はこれがうまくいくと思いますが、使用して '私は追加する必要がありますか? – MattCucco

+0

コンテキストを新しいコンテキストとして使用する – bwyn

+0

インポートのために申し訳ありません。私はあなたのコードを実装したとき、私に "Dim Context as New Context()"というエラーが出ました。インテリセンスを使用すると、それが示唆するインポートのいずれかがエラーを修正することはありません。 – MattCucco

関連する問題