-1

I am wanting to save a record in a database using a simple LINQ statement. I am finding it is not possible to use a Convert.ToInt32 inside the linq statement like below:

using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = Convert.ToInt32(formId);
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

I can certainly do the conversion before the LINQ statement, was curious to know if that is my only option.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Jon Harding
  • 4,928
  • 13
  • 51
  • 96

3 Answers3

0

I would Convert.ToInt32(formId) before you get to the using statement.

Linq does not like Convert statements depending on the ORM

Check this out Problem with converting int to string in Linq to entities

Community
  • 1
  • 1
Mike Hewitt
  • 682
  • 5
  • 11
  • Read the question more carefully: "I can certainly do the conversion before the LINQ statement, was curious to know if that is my only option." – htxryan Aug 26 '13 at 21:35
0

Did you try using int.Parse() or int.TryParse()? Also, why are you not able to use Convert.ToInt32()? Are you getting any errors?

Siva
  • 396
  • 6
  • 12
  • No, `Convert.ToInt32()` can be used OK. He just wants to know if there is another way to do it. `int.Parse` will also do it if the `formId` is string. – King King Aug 26 '13 at 21:57
  • Ok. Anyways, Convert.ToInt32() works only for 32-bit ints. I think he should try using int.Parse() or int.TryParse() for safer conversions. – Siva Aug 26 '13 at 22:00
  • We also have `Convert.ToInt64()` and `int.Parse` is in fact `Int32.Parse`. – King King Aug 26 '13 at 22:02
  • @Siva, `int.Parse` and `int.TryParse` only work on "32-bit int" – sa_ddam213 Aug 27 '13 at 00:47
-1

You can cast the variable like this: (int)formid

You have to check if "formId" can be casted to int.

using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = (int)formId;
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

There is a similar question here: LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression

Community
  • 1
  • 1