I want to get role_code from db.roles based on role_id and return then role_code as the result.
I have tried this
public static string GetRoleCode (int role_id)
{
string result = "";
using (var db =new DbContext())
{
result = db.roles
.Where(r => r.Id == role_id)
.Select(r => new
{
}).FirstOrDefault();
}
return result;
}
What's missing from my code?
CodePudding user response:
Since your result
is a string
, you can't return with anonymous
type in .Select()
.
You should just return the role code as:
.Select(r => r.Code) // Assume this field you need to return
result = db.roles
.Where(r => r.Id == role_id)
.Select(r => r.Code)
.FirstOrDefault();
Or
If you use C# 6 or above, you can use Null conditional operator as below:
result = db.roles
.FirstOrDefault(r => r.Role_Id == role_id)?
.Code;