Linq to SQL生成字符串比较

问题描述 投票:-1回答:1

提供以下课程,

public class MyClass
{
    public string Property { get; set; } //mapped to column 'property'
}

public class MyContext : DbContext
{
    public DbSet<MyClass> MyClasses { get; set; } //mapped to table dbo.MyClasses
}

我正在尝试使用Linq to SQL和EF Core 3.1生成以下SQL请求。

SELECT * FROM dbo.MyClasses
WHERE property > 'constant'

感谢任何帮助。


尝试1:

var result = dbContext.MyClasses.Where(c => c.Property > "constant").ToList();

//Does not compile

尝试2:

var result = dbContext.MyClasses.Where(c => c.Property.CompareTo("constant") > 0).ToList();

//SELECT * FROM dbo.MyClasses
//WHERE
//CASE                                                
//  WHEN property  = 'constant' THEN 0  
//  WHEN property  > 'constant' THEN 1  
//  WHEN property  < 'constant' THEN -1    
//END > 0
c# sql-server entity-framework linq-to-sql ef-core-3.0
1个回答
0
投票

作为替代,您可以使用原始SQL:

dbContext.MyClasses
    .SqlQuery("SELECT * FROM dbo.MyClasses WHERE property > @id", 
        new SqlParameter("@id", 1))
  .ToList<MyClass>();
© www.soinside.com 2019 - 2024. All rights reserved.