Reputation: 77
I'm trying to query my database using Entity Framework, but I receive the following error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.'
This is the relevant code part:
string gendercode = txtGenderNo.Text;
using (var dbcontext = new Entities())
{
var GenderName = dbcontext
.Genders
.Where(u => u.Code == Convert.ToInt32(gendercode))
.Select(u => u.GenderType)
.SingleOrDefault();
txtGenderName.Text = GenderName;
}
public int Code { get; set; }
public string GenderType { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Gender> Genders { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
Upvotes: 0
Views: 984
Reputation: 534
Convert your gendercode
outside the query.
string gendercode = txtGenderNo.Text;
using (var dbcontext = new Entities())
{
var something = Convert.ToInt32(gendercode);
var GenderName = dbcontext
.Genders
.Where(u => u.Code == something)
.Select(u => u.GenderType)
.SingleOrDefault();
txtGenderName.Text = GenderName;
}
It should work this way.
Upvotes: 1
Reputation: 4658
Entity Framework tries to translate your C# code into SQL. Not everything is translatable - only a certain subset is supported by the Entity Framework driver. In your case the solution is easy: convert genderCode
to int
before the LINQ query and use that value in the query:
var genderCodeAsInt = Convert.ToInt32(gendercode);
using (var dbcontext = new Entities())
{
var GenderName = dbcontext
.Genders
.Where(u => u.Code == genderCodeAsInt)
.Select(u => u.GenderType)
.SingleOrDefault();
txtGenderName.Text = GenderName;
}
Upvotes: 4