开发者

SQL ADO.Net Entity LINQ question

开发者 https://www.devze.com 2023-03-02 05:58 出处:网络
I have a small question about my project you could not know, I understand. But perhaps I have a very simple fault in my following function you could see?

I have a small question about my project you could not know, I understand. But perhaps I have a very simple fault in my following function you could see?

<OperationContract()>
Public Function GetBestFahrer() As Autofahrer
    Dim Database As New Model1Container
    Dim Fahrer As Autofahrer = From d In Database.AutofahrerSet Where d.Unfälle = 0 Select d Order By d.Unfälle Ascending
    If Fahrer Is Nothing Then
        Fahrer = Autofahrer.CreateAutofahrer(0, "Testfahrer", DateTime.Now, 0)
        Database.AutofahrerSet.AddObject(Fahrer)
        Database.SaveChanges()
    End If

    Return Fahrer

End Function

Error message on line with "Dim Fahrer As Autof开发者_StackOverflowahrer = ..."

Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[SilverlightApplication4.Web.Autofahrer]' to type 'SilverlightApplication4.Web.Autofahrer'.


Fahrer is a single object
From d In Database.AutofahrerSet Where d.Unfälle = 0 Select d Order By d.Unfälle Ascending does not give you a single object

It looks like you want to see if something exists and then create it if it doesn't.

Try something like this

Dim myCount as integer = (From d In Database.AutofahrerSet Where d.Unfälle = 0 Select d).Count()
if myCount = 0 then
    Fahrer = Autofahrer.CreateAutofahrer(0, "Testfahrer", DateTime.Now, 0)
    Database.AutofahrerSet.AddObject(Fahrer)
    Database.SaveChanges()
else
    Fahrer = (From d In Database.AutofahrerSet Where d.Unfälle = 0 Select d Order By d.Unfälle Ascending).First()
End If
0

精彩评论

暂无评论...
验证码 换一张
取 消