1

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. I don't want it to be IEnumerable so 'Database.SqlQuery' doesn't work for me.

example: there is Product table in db, which contains {Id,Name,CategoryId} and there is Category table in db, which contains {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.

I solved this problem using Interceptor, Here is the solution:

  1. Create a Dbset in your context like this: public DbSet<Model.MyView> MyViews { get; set; }

  2. Create DbCommandInterceptor, and apply it to your entity framework configuration

  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 + ")");

Farzin a
  • 11
  • 2

1 Answers1

0

You can execute raw SQL queries with EF:

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

Z .
  • 12,657
  • 1
  • 31
  • 56