Can you match the results of a manual SQL query with objects in the Entity Framework?

In LINQ, you can write a manual SQL query, extract the results from it and LINQ "map" them to the corresponding properties of your model classes (or at least I'm sure I read that you can do this).

Is it possible to do something like this in the Entity Framework?

I have a web application using EF, and its use by the processor is ridiculously large compared to the traffic that it has, and profiling it on my machine, all this time (presumably) spent on DB functions, and the largest part of this time (> 85%) is spent on the SQL "generation" EF and does things until the query is actually executed.

So, my reasoning is that I can just log in and hard code the SQL queries, but still use my populated model properties in my view.

Is it possible? If so, how do I do this?

Thank!
Daniel

+3
source share
2 answers

So what do you want to do is hydrate an object from IDataReader? It's pretty easy to write code to do this (hint: reflection! Either you can get fancy and use a member initialization expression), or you can google for many existing implementations on the Internet.

EF, ObjectContext.ExecuteStoreQuery<T> ObjectContext.Translate<T>, DbDataReader.

+4

1 ObjectContext.SqlQuery EF 4.0

@Jason, :

IEnumerable<MiniClient> results = 
   myContext.SqlQuery<MiniClient>("select name,company from client");

: https://msdn.microsoft.com/en-us/library/dd487208.aspx

  1. DbContext.Database.SqlQuery, EF 4.1 +

Entity Framework 4.1+ DbContext ObjectContext, :

DbContext myContext= new DbContext();
IEnumerable<MiniClient> results =
  myContext.SqlQuery<MiniClient>("select name,company from client");

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

  1. dynamic

, , MiniClient?

, :

IEnumerable<dynamic> results =
  myContext.Clients.Select( c => new {Name = c.Name, Firstname = c.Firstname});

. MiniClient DbContext. (= DbSet<T>)

0

Source: https://habr.com/ru/post/1771794/


All Articles