gpt4 book ai didi

c# - 如何查询所有实现接口(interface)的表

转载 作者:太空狗 更新时间:2023-10-30 00:19:01 25 4
gpt4 key购买 nike

我已经为我的一些实体类实现了一个接口(interface):

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; }
}

然后我将其添加到 DbContext:

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

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

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

我得到以下异常:

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.

最佳答案

我会选择这样的东西:

创建这个扩展方法

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)));
}
}

然后像这样使用它:

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

关于c# - 如何查询所有实现接口(interface)的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com