32

In MSSQL you can convert a string into an integer like this:

CONVERT(INT, table.column)

Is there any C# expression that Linq to SQL would translate to this?

In C# you can normally do the same by using int.Parse(), but unfortunately, trying to use int.Parse() in a Linq query results in an error:

Method 'Int32 Parse(System.String)' has no supported translation to SQL.

Is there any C# expression that Linq to SQL would translate to CONVERT(INT, ...)?

Timwi
  • 65,159
  • 33
  • 165
  • 230

3 Answers3

34

C# has Convert.ToInt32() which should do what you're looking for.

Eric
  • 92,005
  • 12
  • 114
  • 115
  • 4
    LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression. – Sisyphus Apr 03 '19 at 10:52
11

Convert.ToInt32 should work. Check out this article for information on the translations.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112
  • 5
    LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression. – Sisyphus Apr 03 '19 at 10:53
0

for LINQ to entities, if it is simply a mismatch between your model and the DB you can overcome this using a valueconverter with EF Core.

public OnModelCreating(ModelBuilder modelBuilder) {
  modelBuilder.Entity<mymodel>()
              .Property(e => e.myModelIntColumn) // this column is a string in the db
              .HasConversion(new ValueConverter<int?, string>(m => m.HasValue ? m.ToString().Substring(0,10) : null, db => int.Parse(db ?? "0")));
}

and in my LINQ i can then use bit comparison:

MyDBSet.Where( e => (BitsWanted == 0 ||  ( e.myModelIntColumn & BitsWanted ) > 0));
Justin
  • 1,303
  • 15
  • 30