C# Linq to SQL: How to express “CONVERT([…] AS INT)”?

前端 未结 3 1387
甜味超标
甜味超标 2020-12-01 23:21

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 t

3条回答
  •  生来不讨喜
    2020-12-01 23:57

    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()
                  .Property(e => e.myModelIntColumn) // this column is a string in the db
                  .HasConversion(new ValueConverter(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));
    

提交回复
热议问题