简体   繁体   English

如何在实体框架中将查询脚本用作IQueryable或DBSet

[英]How to use query scripts as IQueryable or DBSet in Entity Framework

I'm using entity framework code first to query database, the problem is I'm not allowed to create views in the database, so I should use query scripts in my codes. 我首先使用实体​​框架代码来查询数据库,但问题是我不允许在数据库中创建视图,因此我应该在代码中使用查询脚本。 I want this query script to be considered same as DBSet or IQueryable by entity framework so that I can apply linq queries on it. 我希望此查询脚本被实体框架视为与DBSet或IQueryable相同,以便可以对其应用linq查询。 I don't want it to be IEnumerable so 'Database.SqlQuery' doesn't work for me. 我不希望它是IEnumerable,所以'Database.SqlQuery'对我不起作用。

example: there is Product table in db, which contains {Id,Name,CategoryId} and there is Category table in db, which contains {Id,Name} 示例:db中有Product表,其中包含{Id,Name,CategoryId},db中有Category表,其中包含{Id,Name}

my query script is like this: 我的查询脚本是这样的:

select Id,Name,CategoryId,CategoryName
from Product p
join Category c on p.CategoryId=c.Id

I want to use this query in my code, as if it was a view. 我想在我的代码中使用此查询,就像它是一个视图一样。

Any idea? 任何想法?

ps: The query script is so complicated that I cannot build it with Linq. ps:查询脚本是如此复杂,以至于我无法使用Linq来构建它。

I solved this problem using Interceptor , Here is the solution: 我使用Interceptor解决了这个问题 ,这是解决方案:

  1. Create a Dbset in your context like this: public DbSet<Model.MyView> MyViews { get; set; } 在您的上下文中创建一个Dbset,如下所示: public DbSet<Model.MyView> MyViews { get; set; } public DbSet<Model.MyView> MyViews { get; set; }

  2. Create DbCommandInterceptor, and apply it to your entity framework configuration 创建DbCommandInterceptor,并将其应用于您的实体框架配置

  3. In the Interceptor implement this method: public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) , and modify the command text like this: command.CommandText = command.CommandText.Replace("[dbo].[MyViews]", "(" + MyViewScript + ")"); 在Interceptor中实现此方法: public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) InterceptionContext public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) ,并像这样修改命令文本: command.CommandText = command.CommandText.Replace("[dbo].[MyViews]", "(" + MyViewScript + ")");

You can execute raw SQL queries with EF: 您可以使用EF执行原始SQL查询:

https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx https://msdn.microsoft.com/zh-CN/library/jj592907(v=vs.113).aspx

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM