Reputation: 3
I'm trying to get an int value from a table based on another ID, I'm using EF to do this but I'm getting the error that cannot implicitly convert type int? to int. This field allow null values.
public int GetIDFunctionRT(int id)
{
var mRT = context.OrgFunctions.First(bf => bf.FormerID == id);
return mRT.IDF;
}
I have tried to include ?mRT to deal with the Nullable but not working.
public int GetIDFunctionRT(int id)
{
var mRT = context.OrgFunctions.First(bf => bf.FormerID == id);
return mRT.IDF;
}
Once done, I will get the function ID associated with an id in another table.
Upvotes: 0
Views: 92
Reputation: 6524
As already stated, return type of method is int, yet you are returning int?. Also, your First may throw an exception if nothing is there. In order to make it predictable, I'll use FirstOrDefault
public int? GetIDFunctionRT(int id)
{
var mRT = context.OrgFunctions.FirstOrDefault(bf => bf.FormerID == id);
return mRT?.IDF.HasValue ? mRT?.IDF : 0;
}
Upvotes: 1
Reputation: 18155
You have two options to approach this.
Make the return type Nullable. You can do so by changing the return type to int?
public int? GetIDFunctionRT(int id)
{
var mRT = context.OrgFunctions.First(bf => bf.FormerID == id);
return mRT.IDF;
}
Return int
but assign a default value if it is null.
public int GetIDFunctionRT(int id)
{
var mRT = context.OrgFunctions.First(bf => bf.FormerID == id);
// Where DefaultValue is the value you want to return when it is null,
// could be 0 or anything else depending on your logic.
return mRT.IDF ?? DefaultValue;
}
Upvotes: 1