简体   繁体   English

对实体框架中的不同DbSet使用相同的查询

[英]Using same query for different DbSets in Entity Framework

I have two different views to the same database table and I would like to use same query against both views. 我对同一数据库表有两个不同的视图,并且我想对两个视图使用相同的查询。

I have now following ugly solution where I have basically copy of the query. 我现在有以下丑陋的解决方案,其中我基本上有查询的副本。

DbSet<uvw_MyView1> view1 = entities.uvw_MyView1;
DbSet<uvw_MyView2> view2 = entities.uvw_MyView2;

if(doQueryOnView1)
{
    // huge query
    view1.Where(jada jada)
}
else
{
    // huge query copied here with exception of different DbSet
    view2.Where(jada jada)
}

What I would like to have is more elegant solution. 我想拥有的是更优雅的解决方案。 Basically I want to have same query part for two DbSet's that are in column wise exactly same, but those return different rows. 基本上,我想对按列方式完全相同的两个DbSet具有相同的查询部分,但是它们返回不同的行。 Any ideas? 有任何想法吗?

Add interface containing all properties of your view and implement this interface by both view entities. 添加包含视图的所有属性的接口,并通过两个视图实体实现此接口。 After that create method containing whole your query: 在包含整个查询的create方法之后:

public static IQueryable<T> YourHugeQueryMethod<T>(DbContext context, ...) 
     where T : class, IView, new()
{
    DbSet<T> set = context.Set<T>();
    return set.Where(...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架中跨多个DbSet的查询属性 - Query property across multiple DbSets in Entity Framework 如何首先在实体框架代码中创建 2 个相同类型的 dbset? - How to create 2 dbsets with the same type in Entity Framework code first? 使用反射迭代实现接口的所有Entity Framework DbSet - Iterating all Entity Framework DbSets that implement an Interface using reflection 如何使用Linq / Entity Framework将2个dbSet加入存储库关系请求中 - How do I join 2 dbSets in a repository relationship request using Linq / Entity framework 使用Entity Framework和Linq对不同的表进行相同的选择 - Make the same select to different tables using Entity Framework and Linq 如何使用实体框架添加具有相同数据的不同子对象? - How to add different child objects with the same data using Entity Framework? 如果我在不同时间使用相同Linq查询的不同字段,Entity Framework是否会多次查询数据库? - Does Entity Framework query the database multiple times if I use different fields of the same Linq query at different times? 实体框架-使用相同的DbContext和不同的连接字符串 - Entity Framework - using the same DbContext with different connection strings 使用反射查询实体框架 - Using Reflection to query an entity framework 在Entity Framework 6中使用不同的数据库 - Using different databases with Entity Framework 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM