Search code examples
stringcastingintegerlinq-to-entities

How to convert string to int in linq to entity?


var trnlist = from tr in db.DebtorTransactions
                              join wr in db.Warranties
                      on  tr.ProductID equals Convert.ToInt32(wr.PkfWarranty) into wrtd 
                              from wr1 in db.Warranties
                              join sr in db.SalesReps
                              on wr1.fldSrId equals sr.pkfSrID into wrsr
                              from wr2 in db.Warranties
                              join ag in db.Agentsenter code here
                              on wr2.fldAgentID equals ag.pkfAgentID into wrag
                              select wrtd;

tr.ProductID is an int and wr.PKfWarranty is string.var rustul= convert.toint32(tr.ProductID) doesn't suitable for me.

Is there any built-in function of Linq to entity to do this?


Solution

  • Here you say:

    tr.ProductID is a int

    And then you try:

    convert.toint32(tr.ProductID)

    So... you're trying to convert an int to an int? In a comment you say:

    the best overload method match for int.parse(string) has some invalid arguments

    Well, if you're trying to call int.Parse() and passing it an int then you'd probably get that exact error. I imagine there's no overload for int.Parse() which accepts an int since, well, the value is already an int.

    Let's look back at your problem description:

    tr.ProductID is a int and wr.PKfWarranty is String

    And you want to compare these two values? Then you'll either need to convert tr.ProductID to a string:

    tr.ProductID.ToString()
    

    or convert wr.PKfWarranty to an int:

    int.Parse(wr.PKfWarranty)
    

    A few things to note:

    • Converting from an int to a string is pretty safe, I doubt you'll ever have problems with that. However, converting from a string to an int assumes that the string can be converted to an int. This won't be the case if the string has anything in it that's not an int, or has a number too large to fit into the int data type. int.TryParse() exists for this purpose, but can be tricky to use in an in-line LINQ statement, especially when that statement is an expression tree which needs to produce SQL code.
    • If you convert the int to a string, there are different ways to compare strings. Depending on whether this is happening in resulting SQL code or in C# code makes a difference. If the latter, string.Equals() is the preferred method.