如何查询实现接口的所有表 [英] How to query all tables that implement an interface

查看:807
本文介绍了如何查询实现接口的所有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现一个接口,用于我的一些实体类:

 公共部分类订单:IReportable
{
   公共字符串表名{{返回订单; }}
}公共部分类客户:IReportable
{
 公共字符串表名{{返回客户; }}
}
公共接口IReportable
{
    字符串表名{获得; }
}

然后我已将此添加的DbContext:

  public虚拟DbSet< IReportable> IReportable {搞定;组; }

当我尝试查询实现此接口(如下图所示)的所有表:

  =从reportabletable在db.IReportable VAR结果
             其中,reportabletable.TableName == TABLE_NAME
            选择reportabletable

我得到了以下异常:


  

类型'Report.DataAccess.IReportable没有映射。检查
  该类型已无法使用忽略方法被明确排除
  或NotMappedAttribute数据注解。验证类型是
  定义为一类,是不是原始的或一般,并没有继承
  从EntityObject。



解决方案

我会去是这样的:

创建此扩展方法

 公共静态类DbContextExtensions
{
    公共静态的IEnumerable< T> SETOF< T>(此的DbContext的DbContext)其中T:类
    {
        返回dbContext.GetType()。Assembly.GetTypes()
            。凡(类型=>的typeof(T).IsAssignableFrom(类型)及和放大器;!type.IsInterface)
            .SelectMany(T => Enumerable.Cast< T>(dbContext.Set(T)));
    }
}

和使用这样的:

 使用(VAR DB =新dbEntities())
{
 VAR的结果=从reportabletable在db.SetOf< IReportable>()
         其中,reportabletable.TableName == TABLE_NAME
        选择reportabletable
}

I have implemented an interface for some of my entity classes:

public partial class Order : IReportable
{
   public string TableName { get { return "Order"; } }
}

public partial class Client: IReportable
{
 public string TableName { get { return "Client"; } }
}


public interface IReportable
{
    string TableName { get; }
}

Then I added this to the DbContext:

public virtual DbSet<IReportable> IReportable { get; set; }

When I try to query all the tables that implement this interface (as shown here):

var result = from reportabletable in db.IReportable
             where reportabletable.TableName == table_name
            select reportabletable

I get the following exception:

The type 'Report.DataAccess.IReportable' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive or generic, and does not inherit from EntityObject.

解决方案

I would go for something like this:

Create this extension method

public static class DbContextExtensions
{
    public static IEnumerable<T> SetOf<T>(this DbContext dbContext) where T : class
    {
        return dbContext.GetType().Assembly.GetTypes()
            .Where(type => typeof(T).IsAssignableFrom(type) && !type.IsInterface)
            .SelectMany(t => Enumerable.Cast<T>(dbContext.Set(t)));
    }
}

And use it like this:

using (var db = new dbEntities())
{
 var result = from reportabletable in db.SetOf<IReportable>()
         where reportabletable.TableName == table_name
        select reportabletable
}

这篇关于如何查询实现接口的所有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆