简体   繁体   English

C# Linq to SQL:如何表达“CONVERT([...] AS INT)”?

[英]C# Linq to SQL: How to express "CONVERT([...] AS INT)"?

In MSSQL you can convert a string into an integer like this:在 MSSQL 中,您可以将字符串转换为整数,如下所示:

CONVERT(INT, table.column)

Is there any C# expression that Linq to SQL would translate to this? Linq to SQL 是否有任何 C# 表达式会转换成这个?

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:在 C# 中,您通常可以使用int.Parse()执行相同的操作,但不幸的是,尝试在 Linq 查询中使用int.Parse()导致错误:

Method 'Int32 Parse(System.String)' has no supported translation to SQL.方法“Int32 Parse(System.String)”不支持转换为 SQL。

Is there any C# expression that Linq to SQL would translate to CONVERT(INT, ...) ? Linq to SQL 是否有任何 C# 表达式会转换为CONVERT(INT, ...)

C# 有Convert.ToInt32()应该做你正在寻找的。

Convert.ToInt32 should work. Convert.ToInt32应该可以工作。 Check out this article for information on the translations.查看这篇文章以获取有关翻译的信息。

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.对于 LINQ to entity,如果它只是您的模型和数据库之间的不匹配,您可以使用带有 EF Core 的 valueconverter 来克服这个问题。

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:然后在我的 LINQ 中,我可以使用位比较:

MyDBSet.Where( e => (BitsWanted == 0 ||  ( e.myModelIntColumn & BitsWanted ) > 0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM