RG-3
RG-3

Reputation: 6188

How to get nullable item from a LINQ2SQL query?

I have a LINQ2SQL query for retrieving an ID (PK, not null). Here is that query:

int masterEntityID;
int payeeID;
int chargePayeeID;
try
{
    using (TestDataContext os = new TestDataContext())
    {
        string entityName = tbSearch.Text;

        var getMasterID = from r in os.Entities
                          where r.Name == entityName
                          select r.ID; 

        masterEntityID = getMasterID.First(); //this is working FINE!

        var getPayeeID = from pid in os.Entities
                         where pid.Name == entityName
                         select pid.Payee_ID;

        payeeID = getPayeeID.First(); //This is giving me an err: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)   



    };

Both the datatypes: ID and Payee_ID are of int. But ID is Pkey and Payee_ID is Not!

How to get the value from getPayeeID to payeeID? Thanks!

Upvotes: 0

Views: 114

Answers (5)

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17784

it seems that Payee_ID property of your entity is nullable that is because it represents a nullable column in the database. so, you should not be receiving its value in int that is not nullable. you can get its value in nullable int like.

int? payeeID = payeeID = getPayeeID.FirstOrDefault(); 

or

var payeeID = payeeID = getPayeeID.FirstOrDefault(); 

later you can check if payeeID value was null or not using

if(payeeID.HasValue)
{
        int x = payeeID.Value; //Value property of nullable int is an integer value and accessing it would through exception if HasValue property is false
}

Upvotes: -1

zapico
zapico

Reputation: 2396

You can use FirstOrDefault() or declare payeeID as a int? and then use it as you want (if it is null you should try to do anything...)

Upvotes: 1

Maged Samaan
Maged Samaan

Reputation: 1752

getPayeeID.First().GetValueOrDefault()

Upvotes: 3

Matt Ellen
Matt Ellen

Reputation: 11592

Since the value is int? you can get the int from it using the Value property:

payeeID = getPayeeID.First().Value;

int? is shorthand for Nullable<int>

Upvotes: 1

Andy Rose
Andy Rose

Reputation: 16974

If your confident that Payee_Id won't ever be null then just cast the value:

payeeID = (int)getPayeeID.First();

Upvotes: 2

Related Questions