私のプログラム内のユーザーによって作成された最後のドキュメントに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
1)一般的なSQLには、大文字と小文字が区別されていないので、あなたはshouldn ToLowerに電話する必要はありません。 2)このコードに問題はありますか? –
このコードは現在のところ動作しませんが、データテーブルや行を使用しない代わりに、ほとんどのコードを再フォーマットして、代わりにienumerablesを使用しています。 – MattCucco
http://stackoverflow.com/questions/157786/how-do-i-get-the-max-row-with-a-group-by-in-linq-query –