1

I've got the following LINQ:

        var items = from n in db.Roles
                    where n.importID == importID
                    select n;

The "importID" is a string as parameter and a string? for the database object. If importID is null in Database there shall be no match. How to achieve this?

Compiler message:

Operator '==' cannot be applied to operands of type 'string?' and 'string'

SDwarfs
  • 3,189
  • 5
  • 31
  • 53

4 Answers4

6

A string is a reference type, and so is already nullable (i.e. you can set it to null). The only purpose of the Nullable type is to allow value types (such as integers, doubles, etc.) to be set to null. The fix is to declare importId as string, not string?.

RB.
  • 36,301
  • 12
  • 91
  • 131
  • I'm aware of that. And yes, i want to have importID to be nullable (as not all entries will be imported ones [user created] and therefore have an importID). – SDwarfs Sep 18 '12 at 08:25
  • @StefanK. but it is impossible to define a nullable string when *string is already nullable*. The compiler doesn't allow it! – Adam Sep 18 '12 at 08:27
  • The compiler does... there isn't even a warning. – SDwarfs Sep 18 '12 at 08:28
  • 2
    `string?` and a value that can be `DbNull` are two *very* different things. See [this question](http://stackoverflow.com/questions/682429/how-can-i-query-for-null-values-in-entity-framework). `string?` will *always* give you a compiler error (`The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'`). – Adam Sep 18 '12 at 08:32
  • Hm, ok... as this is possibly a bug in Entity Framework, I'll test this and investigate it in more detail. Thanks at least for the warning... – SDwarfs Sep 18 '12 at 08:36
4
var items = from n in db.Roles
            where n.importID.HasValue && n.importId.Value == importID
            select n;
JConstantine
  • 3,980
  • 1
  • 33
  • 46
0

Also you can use .GetValueOrDefault()

In Short Query can be...

var items = from n in db.Roles
                where n.importID == importID.GetValueOrDefault()
                select n;
Mayank Pathak
  • 3,621
  • 5
  • 39
  • 67
0
var items = from n in db.Roles
                    where !string.IsNullOrEmpty(n.importID) && n.importID == importID
                    select n;
Pushpendra
  • 814
  • 1
  • 6
  • 17