3

有没有办法可以使以下数据库查询生成器通用?

private IQueryable<Foo> ByName(IQueryable<Foo> dbQuery, Query query)
{
    string[] searchTerms = query.Data.Replace(" ","").ToLower().Split(',');

    if (query.Exclude)
    {
        return dbQuery.Where(x => searchTerms.All(
            y => y != x.Name.Replace(" ", "").ToLower()));
    }

    return dbQuery.Where(x => searchTerms.Any(
        y => y == x.Name.Replace(" ", "").ToLower()));
}

对于 Foo 的许多不同属性,我都有相同的功能。ByCounty、ByTown、ByStreet 等

我之前写过一些返回 linq 的函数,如下所示

public Expression<Func<Foo, bool>> FoosAreWithinDistanceFromGeocode(
    double distance, Geocode geocode)
{
    double distanceSquare = distance * distance;
    return foo => ( SqlFunctions.Square((double)(
        foo.Address.Geocode.Easting - geocode.Easting)) +
        SqlFunctions.Square((double)(fooAddress.Geocode.Northing - 
        geocode.Northing)) ) <= distanceSquare;
}

但我似乎无法找到 Linq-to-SQL 的东西是否不能使用泛型,或者是否可以将属性作为泛型传递等等。


编辑:我通常为单个搜索词工作。

Where [query.Data == "Foo1"]

return dbQuery.Where(SearchMatch("Name", query.Data));

public Expression<Func<Foo, bool>> SearchMatch(string propertyName, string searchTerm)
{
    var foo = Expression.Parameter(typeof(Foo), "foo");
    var prop = Expression.Property(foo, propertyName);
    var search = Expression.Constant(searchTerm);
    var equal = Expression.Equal(prop, search);

    return Expression.Lambda<Func<Foo, bool>>(equal, foo);
}

任何人都知道如何使它适用于字符串数组?

4

2 回答 2

6

您需要定义一个接口来公开您要访问的属性,如下所示:

public interface IHaveName
{
    string Name { get; }
}

然后,在您的类上,您将实现接口:

public class Foo : IHaveName

如果您使用的是从 DBML 文件生成的类,这些类会用partial关键字标记,因此实现接口就像创建一个新文件并插入一样简单:

public partial class Foo : IHaveName

由于该属性已在从 .dbml 文件生成的其他.cs 文件中声明为公共,因此该接口是隐式实现的。

最后,您将重写您的ByName方法以采用具有实现您的接口的约束的泛型类型参数IHaveName

private IQueryable<T> ByName<T>(IQueryable<T> dbQuery, Query query)
    where T : IHaveName
{
    // Everything else is the same.

对于您的其他属性(以及使用它们的方法),您可以将它们聚合到一个接口中,或者根据您的需要将它们分开。


根据您的编辑,如果要动态创建表达式,则不必放弃编译时安全性:

public Expression<Func<Foo, bool>> SearchMatch(
    Expression<Func<Foo, string>> property, string searchTerm)
{
    var foo = Expression.Parameter(typeof(Foo), "foo");
    // Get the property info from the property expression.
    var prop = Expression.Property(foo, 
        (property.Body as MemberExpression).Member as PropertyInfo);
    var search = Expression.Constant(searchTerm);
    var equal = Expression.Equal(prop, search);

    return Expression.Lambda<Func<Foo, bool>>(equal, foo);
}

然后你这样称呼它:

var expression = SearchMatch(f => f.Name, "searchTerm");

这可确保您传递给的属性SearchMatch实际存在于Foo. 请注意,如果您想让其他标量属性类型通用,您可以执行以下操作:

public Expression<Func<Foo, bool>> SearchMatch<T>(
    Expression<Func<Foo, T>> property, T searchTerm)
{
    var foo = Expression.Parameter(typeof(Foo), "foo");
    // Get the property info from the property expression.
    var prop = Expression.Property(foo, 
        (property.Body as MemberExpression).Member as PropertyInfo);
    var search = Expression.Constant(searchTerm);
    var equal = Expression.Equal(prop, search);

    return Expression.Lambda<Func<Foo, bool>>(equal, foo);
}
于 2012-11-01T15:42:43.020 回答
-1

如果我理解你想要实现的反思可能会对你有所帮助。至少如果你玩得很好。这是一个简化但有效的示例

internal class Program
{
    private class Data
    {
        public string Name { get; set; }
        public string Address { get; set; }

        public override string ToString()
        {
            return String.Format("My name is {0} and I'm living at {1}", Name, Address);
        }
    }

    static Expression<Func<Data,bool>> BuildExpression(PropertyInfo prop, IQueryable<string> restrict)
    {
        return (data) => !restrict.Any(elem => elem == prop.GetValue(data, null));
    }

    static IQueryable<Data> FilterData(IQueryable<Data> input, Expression<Func<Data, bool>> filter)
    {
        return input.Where(filter);
    }

    public static void Main (string[] args)
    {
        List<Data> list = new List<Data>()
                               {
                                   new Data {Name = "John", Address = "1st Street"},
                                   new Data {Name = "Mary",Address = "2nd Street"},
                                   new Data {Name = "Carl", Address = "3rd Street"}
                               };

        var filterByNameExpression = BuildExpression(typeof (Data).GetProperty("Name"),
                                                     (new List<string> {"John", "Carl"}).AsQueryable());

        var filterByAddressExpression = BuildExpression(typeof(Data).GetProperty("Address"),
                                                     (new List<string> { "2nd Street"}).AsQueryable());

        IQueryable<Data> filetedByName = FilterData(list.AsQueryable(), filterByNameExpression);
        IQueryable<Data> filetedByAddress = FilterData(list.AsQueryable(), filterByAddressExpression);

        Console.WriteLine("Filtered by name");
        foreach (var d in filetedByName)
        {
            Console.WriteLine(d);
        }

        Console.WriteLine("Filtered by address");
        foreach (var d in filetedByAddress)
        {
            Console.WriteLine(d);
        }

        Console.ReadLine();
    }

但是,我几乎可以肯定它不适用于 LINQ-to-SQL。解决它的一种方法是IQueryable在将其传递给此类过滤方法之前将其具体化(例如,通过调用ToList它们)。

于 2012-11-01T15:51:26.357 回答