我想用实体框架做这样的事情:
db.Customers.OrderBy(c => c.MoneySpent/c.OrdersPlaced)
无需像这样设置任何除以零的保护:
db.Customers.OrderBy(c => c.OrdersPlaced == 0 ? 0.0 : c.MoneySpent/c.OrdersPlaced)
为了做到这一点,我尝试了几件事,但我得到的最接近解决问题的是禁用ARITHABORT
and ANSI_WARNINGS
,我在上下文的构造函数中这样做了:
public class DatabaseContext : DbContext
{
static DatabaseContext()
{
Database.SetInitializer<DatabaseContext>(null);
}
public DatabaseContext()
: base("Name=DatabaseContext")
{
Database.ExecuteSqlCommand("SET ANSI_DEFAULTS OFF");
Database.ExecuteSqlCommand("SET ARITHABORT OFF");
Database.ExecuteSqlCommand("SET ANSI_WARNINGS OFF");
}
// Tables that can be queried directly
public DbSet<Customer> Customers { get; set; }
}
然后当我尝试从我的 Web API 控制器获取结果时,我仍然收到以下错误:
...failed to serialize the response body for content type 'application/json...
InnerException: Divide by zero error encountered...
当我查看 SQL Server Profiler 的情况时,似乎每次进行新查询时都会ANSI_WARNINGS
重置。ON
有没有办法改变默认值ANSI_WARNINGS
,使其停留OFF
在查询之间?