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'

2
  • string? is not a valid expression in C#. Commented Sep 18, 2012 at 8:24
  • It is... at least using Entity Framework this means a string that is nullable (e.g. can be set to DbNull). Commented Sep 18, 2012 at 8:27

4 Answers 4

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?.

Sign up to request clarification or add additional context in comments.

5 Comments

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).
@StefanK. but it is impossible to define a nullable string when string is already nullable. The compiler doesn't allow it!
The compiler does... there isn't even a warning.
string? and a value that can be DbNull are two very different things. See this question. 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<T>').
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...
4
var items = from n in db.Roles
            where n.importID.HasValue && n.importId.Value == importID
            select n;

2 Comments

@StefanK. no, it's not. See the other answer.
@codesparkle: I would consider your comment, if you would explain, why the code is compiling and seems logical.
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;

Comments

0
var items = from n in db.Roles
                    where !string.IsNullOrEmpty(n.importID) && n.importID == importID
                    select n;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.