BornToCode
BornToCode

Reputation: 10213

sql query with entity framework

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.

Upvotes: 0

Views: 12510

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109165

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

Upvotes: 2

Shyju
Shyju

Reputation: 218792

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.

Upvotes: 9

Related Questions