简体   繁体   English

Microsoft实体框架中使用的原始SQL查询是否返回对象?

[英]Does a raw SQL query used in the Microsoft Entity Framework return objects?

I personally like SQL, but I realize I probably need to follow the EF design. 我个人喜欢SQL,但是我意识到我可能需要遵循EF设计。 At times and with other team members, SQL will be used. 有时与其他团队成员,SQL 被使用。 When a Raw SQL Query is made, does it return objects/properties for my C# code? 进行原始SQL查询时,它是否为我的C#代码返回对象/属性? If I have five tables mapped, and I do a raw query, are corresponding properties returned? 如果我映射了五个表,并且进行了原始查询,是否返回了相应的属性?

The answer is yes. 答案是肯定的。 You need to define your entity class for the result of your raw SQL Query, remember to make the name of the properties exactly the same with the name of returned columns in your query. 您需要为原始SQL查询的结果定义实体类,请记住使属性名称与查询中返回的列名称完全相同。

context.Database.SqlQuery<YourEntity>("your query").ToList();

With EF, you have to create and maintain the POCO for your raw query, and your query text will probably languish inside double quotes somewhere. 使用EF,您必须为原始查询创建和维护POCO,并且查询文本可能会在某处的双引号内变得不可用。 Why not grab QueryFirst ? 为什么不抓住QueryFirst Your sql will be in .sql file, and the wrapper code, including POCO will be generated and managed for you. 您的sql将位于.sql文件中,并且将为您生成和管理包装器代码(包括POCO)。 And there are numerous other advantages ! 并且还有许多其他优点

You don't have to use one approach exclusively. 您不必只使用一种方法。 Lots of folk use EF, then Dapper or something like it when they need/want to "revert" to SQL. 很多人在需要/想要“恢复”到SQL时使用EF,然后使用Dapper或类似的工具。 QueryFirst isn't an ORM and doesn't replace EF. QueryFirst不是ORM,也不替代EF。 Obviously if you let EF manage your schema, (code first, model first) then non-EF queries risk being walloped by EF schema changes. 显然,如果让EF管理架构(先编码,先建模),则非EF查询可能会因EF架构更改而陷入困境。 But with QueryFirst at least, you can "recompile" your queries to assure they're working and still return what you need after EF has changed your schema. 但是至少使用QueryFirst,您可以“重新编译”查询以确保它们正在运行,并且在EF更改架构后仍返回所需的内容。

Disclaimer: I wrote QueryFirst. 免责声明:我写了QueryFirst。

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

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