简体   繁体   English

实体框架的SQL查询

[英]sql query with entity framework

How can I use sql query, in sql language, if I used entity framework to make the connection? 如果我使用实体框架进行连接,如何使用sql语言使用sql查询? I understood from this post that ObjectContext.ExecuteStoreQuery won't help because it works only with some queries (not 1:1 to sql language). 我从这篇文章中了解到ObjectContext.ExecuteStoreQuery将无济于事,因为它仅适用于某些查询(不适用于sql语言的1:1)。

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. 这里提到的另一个选项是使用ObjectContext.Connection并从那里编写“经典” ADO.NET代码,但是我只是想不通如何。

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. 我知道Linq-To-Sql存在,但我更喜欢使用sql语言,它对我来说看起来更简单,并且我对此更加熟悉。

use the Database.SqlQuery method to execute SQL queries 使用Database.SqlQuery方法执行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. 假设DataContext类对象中有context ,这应该可以工作。

Not an answer, but I have to... 没有答案,但我必须...

I prefer to use sql language 我更喜欢使用sql语言

Do yourself a favour and "forget" SQL! 帮自己一个忙,“忘记” SQL! Linq is really not that hard. Linq确实不是那么难。 SQL in string literals is maintenance hell. 字符串文字中的SQL是维护地狱。 Linq is strong-typed so the compiler guards you against code corruption. Linq是强类型的,因此编译器可防止代码损坏。 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. 您的声明对Linq来说是小菜一碟。

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

Well, just an advice :D 好吧,只是一个建议:D

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

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