我有一个MVC项目,它为每个模型项目的用户输出一个可为空的DateTime(DateTime?
)作为字符串,如下所示(我的用户界面有分页,所以我只对少量的记录 - 换句话说,这部分是可以的):
foreach (DocumentEvent item in Model.items)
@(item?.TimeUtc?.ToString() ?? "N/A")
我想添加搜索功能。我尝试按如下方式进行搜索,但这不符合要求,因为AsEnumerable
实现了我的列表,我现在处于C#世界,枚举每条记录:
using (var context = new ClientEventsContext())
var items = context.Events.AsEnumerable().Where(x => {
(x?.TimeUtc?.ToString() ?? "N/A").Contains(model.search)
});
相反,我想利用我的SQL Server数据库。如何为没有AsEnumerable
的上述代码构建一个SQL Server友好的查询,它将产生与我当前逻辑相同的结果?
答案 0 :(得分:4)
以下是如何构建和使用以M/d/yyyy h:mm:ss tt
格式从日期到字符串的LINQ to Entities兼容转换。而是将该怪物嵌入查询中,我将使用自定义“标记”方法并使用ExpressionVisitor
绑定实现。这样,您可以根据需要进行实验和更改格式(甚至添加一些控制参数),而不会影响查询的可读性。
首先,实施:
public static class EFExtensions
{
public static string ToCustomDateFormat(this DateTime value)
{
// Should never happen
throw new InvalidOperationException();
}
public static IQueryable<T> ApplyCustomDateFormat<T>(this IQueryable<T> source)
{
var expression = new CustomDateFormatBinder().Visit(source.Expression);
if (source.Expression == expression) return source;
return source.Provider.CreateQuery<T>(expression);
}
class CustomDateFormatBinder : ExpressionVisitor
{
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.DeclaringType == typeof(EFExtensions) && node.Method.Name == "ToCustomDateFormat")
{
var date = Visit(node.Arguments[0]);
var year = DatePart(date, v => DbFunctions.Right("0000" + v.Year, 4));
var month = DatePart(date, v => v.Month.ToString());
var day = DatePart(date, v => v.Day.ToString());
var hour = DatePart(date, v => (1 + (v.Hour + 11) % 12).ToString());
var minute = DatePart(date, v => DbFunctions.Right("0" + v.Minute, 2));
var second = DatePart(date, v => DbFunctions.Right("0" + v.Second, 2));
var amPM = DatePart(date, v => v.Hour < 12 ? "AM" : "PM");
var dateSeparator = Expression.Constant("/");
var timeSeparator = Expression.Constant(":");
var space = Expression.Constant(" ");
var result = Expression.Call(
typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) }),
Expression.NewArrayInit(typeof(string),
month, dateSeparator, day, dateSeparator, year, space,
hour, timeSeparator, minute, timeSeparator, second, space, amPM));
return result;
}
return base.VisitMethodCall(node);
}
Expression DatePart(Expression date, Expression<Func<DateTime, string>> part)
{
var parameter = part.Parameters[0];
parameterMap.Add(parameter, date);
var body = Visit(part.Body);
parameterMap.Remove(parameter);
return body;
}
Dictionary<ParameterExpression, Expression> parameterMap = new Dictionary<ParameterExpression, Expression>();
protected override Expression VisitParameter(ParameterExpression node)
{
Expression replacement;
return parameterMap.TryGetValue(node, out replacement) ? replacement : node;
}
}
}
然后用法:
var items = context.Events
.Where(x => x.TimeUtc != null &&
x.TimeUtc.Value.ToCustomDateFormat().Contains(model.search))
.ApplyCustomDateFormat();
答案 1 :(得分:3)
我找到了解决方案。这种语法似乎有效:
using (var context = new ClientEventsContext())
var items = context.Events.Where(x => {
x.TimeUtc.HasValue && x.TimeUtc.Value.ToString().Contains(model.search)
});
答案 2 :(得分:2)
使用SqlFunctions库将任何内容转换为Raw Query并在SQL级别执行作业的另一种解决方案,例如:
using (var context = new ClientEventsContext())
var items = context.Events.Where(x =>
SqlFunctions.PatIndex(model.search,
SqlFunctions.DateName('your pattern here', x?.TimeUtc) ?? "N/A").Value > -1
);