实体框架非泛型属性中的通用查询

时间:2014-08-13 14:49:41

标签: entity-framework generics

在Entity框架中,我有像

这样的对象集
public partial class Building
{       
    public int BuildingID { get; set; }
    public string BuildingName { get; set; }
}
public partial class Town
{       
    public int TownID { get; set; }
    public string TownName { get; set; }
}

我想创建一个像

这样的通用查询
T.OrderBy(o=>o.Id).Skip(maxDispItem * (page - 1)).Take(maxDispItem).ToList();

T是通用类,可以是Building或Town,但问题是BuildingIdTownId有不同的名称。我不想将其名称更改为Id并创建界面IIdentity

2 个答案:

答案 0 :(得分:0)

也许你可以尝试这样的事情:

var query = (typeof(T) == typeof(Building) ?
                context.Buildings.Select(b => new { Id = b.BuildingId, Name = b.BuildingName }) :
                context.Towns.Select(t => new { Id = t.TownId, Name = b.TownName }))
            .OrderBy(o => o.Id)...

未经测试,但值得测试...

答案 1 :(得分:0)

您可以创建查找用KeyAttribute修饰的字段的泛型方法,然后按找到的键字段执行排序。我测试过你的模型,效果很好。查看代码段。

<强>的DbContext:

using System.Collections.Generic;
using System.Data.Entity;

namespace ConsoleApplication28.Entities
{
    public class AppDbContext : DbContext
    {
        public AppDbContext()
        {
            Database.Connection.ConnectionString = @"Data Source=NOTEBOOK-PC;Initial Catalog=StackOverflowTest;Integrated Security=True";
            Database.SetInitializer(new AppDbInitializer());
        }

        public DbSet<Town> Towns { get; set; }
        public DbSet<Building> Buildings { get; set; }
    }

    public class AppDbInitializer : DropCreateDatabaseIfModelChanges<AppDbContext>
    {
        protected override void Seed(AppDbContext context)
        {
            context.Buildings.AddRange(new List<Building>
                                       {
                                           new Building {BuildingName = "Building1"},
                                           new Building {BuildingName = "Building2"},
                                       });

            context.Towns.AddRange(new List<Town>
                                       {
                                           new Town {TownName = "Town1"},
                                           new Town {TownName = "Town2"},
                                       });
            context.SaveChanges();
            base.Seed(context);
        }
    }
}

<强>建筑

using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication28.Entities
{
    public class Building
    {
        [Key]
        public int BuildingID { get; set; }
        public string BuildingName { get; set; }
    }
}

<强>镇

using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication28.Entities
{
    public class Town
    {
        [Key]
        public int TownID { get; set; }
        public string TownName { get; set; }
    }
}

<强>程序

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using ConsoleApplication28.Entities;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication28
{
    class Program
    {
        static void Main(string[] args)
        {
            const int maxDispItem = 10;
            const int page = 1;
            var db = new AppDbContext();
            var towns = db.Towns.OrderByKey().Skip(maxDispItem * (page - 1)).Take(maxDispItem).ToList();
            var buildings = db.Buildings.OrderByKey().Skip(maxDispItem * (page - 1)).Take(maxDispItem).ToList();
        }
    }

    public static class Extensions
    {
        /// <summary>
        /// Sorts the elements of a sequence in ascending order according to a key specified using KeyAttribute
        /// </summary>
        public static IOrderedQueryable<T> OrderByKey<T>(this IQueryable<T> source, bool isAsc = true)
        {
            var type = typeof(T);
            var keyProperty = type.GetProperties().Single(x => x.GetCustomAttributes(typeof(KeyAttribute)).Any());
            return source.OrderBy(keyProperty.Name, isAsc);
        }

        #region COPIED FROM THERE http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet

        public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property, bool isAsc)
        {
            return isAsc ? source.OrderBy(property) : source.OrderByDescending(property);
        }
        public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "OrderBy");
        }
        public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "OrderByDescending");
        }
        public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "ThenBy");
        }
        public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "ThenByDescending");
        }
        static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
        {
            string[] props = property.Split('.');
            Type type = typeof(T);
            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;
            foreach (string prop in props)
            {
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                    method => method.Name == methodName
                            && method.IsGenericMethodDefinition
                            && method.GetGenericArguments().Length == 2
                            && method.GetParameters().Length == 2)
                    .MakeGenericMethod(typeof(T), type)
                    .Invoke(null, new object[] { source, lambda });
            return (IOrderedQueryable<T>)result;
        }

        #endregion
    }
}