31

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
  • 63,217
  • 30
  • 158
  • 225

3 Answers3

33

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

Eric
  • 88,339
  • 12
  • 112
  • 115
  • 2
    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
12

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

JP Alioto
  • 44,379
  • 6
  • 86
  • 112
  • 3
    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,059
  • 12
  • 26