【问题标题】:generic function to get entity list from entity从实体获取实体列表的通用函数
【发布时间】:2012-06-28 18:12:40
【问题描述】:

我想创建一个通用函数,我将实体名称传递给它,它会返回该实体类型的列表,如下所示:

private List<Entity> GetEntityList(Entity entity)
{
    return context.entity.ToList();
}

context 是 objectcontext。

请提出解决方案。

【问题讨论】:

  • 您是否有复数的表名(例如输入'Customer',但表名'Customers')?

标签: c# asp.net entity-framework linq-to-entities


【解决方案1】:

这可能会有所帮助:

public static class ObjectContextExtensions
    {
        public static ObjectQuery<TEntity> GetEntities<TEntity>(this ObjectContext context) where TEntity : class {
            var query = from pd in context.GetType().GetProperties()
                        where pd.PropertyType.IsSubclassOf(typeof(ObjectQuery<TEntity>))
                        select (ObjectQuery<TEntity>)pd.GetValue(context, null);
            return query.FirstOrDefault();
        }
    }

用法:

using (var objectContext = new ObjectContext())
            {
                var entities = objectContext.GetEntities<Entity>().ToList();
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多