sql query with entity framework

ado.net entity-framework linq-to-sql objectcontext sql

Question

How can I use sql query, in sql language, if I used entity framework to make the connection? I understood from this post that ObjectContext.ExecuteStoreQuery won't help because it works only with some queries (not 1:1 to sql language).

The other option mentioned there is to use ObjectContext.Connection and write "classic" ADO.NET code from there, but I just can't figure out how.

Can someone please write a very simple code example how can I perform a simple query like

select MAX(customer_id) from Customers 

with the entity framework? I know that Linq-To-Sql exist, but I prefer to use sql language, it looks simpler to me and I am more familiar with it.

1
0
5/23/2017 12:13:48 PM

Accepted Answer

Not an answer, but I have to...

I prefer to use sql language

Do yourself a favour and "forget" SQL! Linq is really not that hard. SQL in string literals is maintenance hell. Linq is strong-typed so the compiler guards you against code corruption. You've got intellisense, far less ceremonial code, it is much easier to express complex queries. And so forth and so on.

Your statement is a piece of cake in Linq.

context.Customers.Max(c => c.customer_id)

Well, just an advice :D

2
6/12/2012 7:53:45 PM

Popular Answer

use the Database.SqlQuery method to execute SQL queries

var maxId= context.Database.
           SqlQuery<int>("select MAX(customer_id) from Customers")
                                                              .SingleOrDefault();

This should work assuming context in your DataContext class object.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow