enb*_*081 5 c# linq asp.net-mvc entity-framework
我已经为我的一些实体类实现了一个接口:
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; }
}
Run Code Online (Sandbox Code Playgroud)
然后我将其添加到DbContext:
public virtual DbSet<IReportable> IReportable { get; set; }
Run Code Online (Sandbox Code Playgroud)
当我尝试查询实现此接口的所有表时(如此处所示):
var result = from reportabletable in db.IReportable
where reportabletable.TableName == table_name
select reportabletable
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
未映射"Report.DataAccess.IReportable"类型.使用Ignore方法或NotMappedAttribute数据批注检查未明确排除类型.验证类型是否已定义为类,不是原始类型还是通用类型,并且不从EntityObject继承.
我会选择这样的东西:
创建此扩展方法
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)));
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
using (var db = new dbEntities())
{
var result = from reportabletable in db.SetOf<IReportable>()
where reportabletable.TableName == table_name
select reportabletable
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |