【发布时间】:2019-01-24 14:04:50
【问题描述】:
我使用 Entity Framework Core 2.1。
我在数据库中有一个标量函数,它增加了指定的天数。 我创建了一个扩展方法来执行它:
public static class AdventureWorks2012ContextExt
{
public static DateTime? ExecFn_AddDayPeriod(this AdventureWorks2012Context db, DateTime dateTime, int days, string periodName)
{
var sql = $"set @result = dbo.[fn_AddDayPeriod]('{dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}', {days}, '{periodName}')";
var output = new SqlParameter { ParameterName = @"result", DbType = DbType.DateTime, Size = 16, Direction = ParameterDirection.Output };
var result = db.Database.ExecuteSqlCommand(sql, output);
return output.Value as DateTime?;
}
}
我尝试在查询中使用标量函数(为了简化我使用 AdventureWorks2012 的事情),如下所示:
var persons =
(from p in db.Person
join pa in db.Address on p.BusinessEntityId equals pa.AddressId
where p.ModifiedDate > db.ExecFn_AddDayPeriod(pa.ModifiedDate, 100, "DayPeriod_day")
select p).ToList();
但得到一个 System.InvalidOperationException: '在前一个操作完成之前在此上下文上启动了第二个操作。不保证任何实例成员都是线程安全的。'
我怎样才能做到这一点?
更新: 在伊万的回答的帮助下,我设法做到了:
var persons =
(from p in db.Person
join bea in db.BusinessEntityAddress on p.BusinessEntityId equals bea.BusinessEntityId
join a in db.Address on bea.AddressId equals a.AddressId
where p.ModifiedDate > AdventureWorks2012ContextFunctions.AddDayPeriod(a.ModifiedDate, 100, "DayPeriod_day")
select p).ToList();
但现在我需要更新已过滤人员的 ModifiedDate。所以我这样做:
var persons =
(from p in db.Person
join bea in db.BusinessEntityAddress on p.BusinessEntityId equals bea.BusinessEntityId
join a in db.Address on bea.AddressId equals a.AddressId
let date = AdventureWorks2012ContextFunctions.AddDayPeriod(a.ModifiedDate, 100, "DayPeriod_day")
where p.ModifiedDate > date
select new { Person = p, NewDate = date }).ToList();
foreach (var p in persons)
p.Person.ModifiedDate = p.NewDate ?? DateTime.Now;
db.SaveChanges();
但得到 System.NotSupportedException: 'Specified method is not supported.'
如何在 select 语句中使用标量函数?
我尝试将查询分成两部分:
var filteredPersons = // ok
(from p in db.Person
join bea in db.BusinessEntityAddress on p.BusinessEntityId equals bea.BusinessEntityId
join a in db.Address on bea.AddressId equals a.AddressId
where p.ModifiedDate > AdventureWorks2012ContextFunctions.AddDayPeriod(a.ModifiedDate, 100, "DayPeriod_day")
select new { Person = p, a.ModifiedDate }).ToList();
var persons = // here an exception occurs
(from p in filteredPersons
select new { Person = p, NewDate = AdventureWorks2012ContextFunctions.AddDayPeriod(p.ModifiedDate, 100, "DayPeriod_day") }).ToList();
【问题讨论】:
-
能否将
fn_AddDayPeriod修改为接受datetime而不是varchar(或当前使用的任何文本类型)? -
fn_AddDayPeriod 是一个相当复杂的函数。这就是我想直接调用它的原因。
-
fn_AddDayPeriod 有三个参数,分别是 DATETIME、INT 和 VARCHAR(100) 类型。我不应该修改这个函数。
-
啊,已经是
datetime,完美。我们可以修改AdventureWorks2012Context类还是不允许的? -
是的,我们可以修改db上下文。
标签: linq entity-framework-core