Reputation: 6188
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
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
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
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
Reputation: 16974
If your confident that Payee_Id won't ever be null then just cast the value:
payeeID = (int)getPayeeID.First();
Upvotes: 2