0

I am learning entity framework and while editing record I received this error:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Please suggest how to fix it. Here is the code for it.

tblUser obj = new tblUser();

using (var ctx = new TestEntities2())
{
    var stud = (from s in ctx.tblUsers
                where s.Id.ToString() == RouteData.Values["Id"].ToString()
                select s).FirstOrDefault();
    obj.Fname = model.Fname;
    obj.Lname = model.Lname;
    obj.Username = model.UserName;
    obj.Email = model.Email;
    obj.PhoneNumber = model.PhoneNumber;

    int num = ctx.SaveChanges();
}
Michael Richardson
  • 4,213
  • 2
  • 31
  • 48
Supreet
  • 2,451
  • 8
  • 25
  • 42
  • possible duplicate of [Entity Framework ToString method](http://stackoverflow.com/questions/18169388/entity-framework-tostring-method) – Aleksei Poliakov Dec 14 '13 at 17:32
  • If `RouteData.Values["Id"]` is a number, then you're better off converting it to a number outside of the `using` and comparing it directly to `s.Id`. – Zev Spitz Dec 14 '13 at 17:51

1 Answers1

2

I think you're receiving the error because RouteData.Values["Id"] is passed as an object, but the underlying type is a string.

If you are expecting a Guid then you should parse the RouteData Value first and compare Guid to Guid. This is generally better practice than comparing string to string. Here's some sample code to get you started. When receiving data from the user, you should always check it for validity first.

using (var ctx = new TestEntities2())
{
    Guid routeId;
    if (Guid.TryParse(RouteData.Values["Id"].ToString, out routeId))
    {
        // var stud = (from s in ctx.tblUsers
                    // where s.Id.ToString() == RouteData.Values["Id"].ToString()
                    // select s).FirstOrDefault();
        var stud = ctx.tblUsers.Find(routeId); // simpler and faster
        // Always check that the query returned something
        if (stud != null)
        {
            // Do stuff
        }
    }
    else
    {
        // display a message to the user that something went wrong
    }
}
Michael Richardson
  • 4,213
  • 2
  • 31
  • 48