开发者

Can I have a condition in the select of a Linq to Entities query?

开发者 https://www.devze.com 2023-02-20 09:10 出处:网络
I want to do this: Dim person = From p In context.persons Order By p.fileNum Select p.ID, p.firstName, p.lastName,

I want to do this:

Dim person = From p In context.persons
  Order By p.fileNum
  Select p.ID,
    p.firstName,
    p.lastName,
    startPenpal = IIf(p.prPenPals.Count > 0,
        p.prPenPals.FirstOrDefault.startProfile, "")

I get this error:

LINQ to Entities does not recognize the method 'System.Object IIf(Boolean, System.Object, System.Object)' method, and this method cannot be translated into a store expression.

I tried

Select p.ID, p.firstName, p.lastName,
    startPenp开发者_如何学Goal = If(i.prPenPals.Count > 0,
        i.prPenPals.FirstOrDefault.startProfile, "")

and I get this error:

Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.

Is there a way to do this? prPenpals can contain zero or one record for each record in Persons. There should probablt be a 1 to 0-1 association between persons and prPenPal, but the model has it as a one to many and I haven't been able to change it.


Your mistake is here, I think:

If(i.prPenPals.Count > 0, i.prPenPals.FirstOrDefault.startProfile, "")

You should make sure you will return the same type for the values. If i.prPenPals.FirstOrDefault.startProfile is a DateTime, then do this:

If(i.prPenPals.Count > 0, i.prPenPals.FirstOrDefault.startProfile, DateAndTime.MinValue)

Not sure about the syntax of VB because I am on C#, but the main idea is the same.

0

精彩评论

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