search
HomeDatabaseMysql TutorialEntity Framework SqlFunctions 教你如何在EF调用sqlserver方法

今天算是研究了一天的SqlFunctions,请教了几个群的牛人,居然发现大伙对这个都比较陌生, 有的甚至直指EF中是不能调用sqlserver里的方法的。 因为之前搞过linq to sql 里面的SqlMethod ,所以觉得EF里面必须是可以的。 首先需要简短介绍一下EF6和EF5,当你N

今天算是研究了一天的SqlFunctions,请教了几个群的牛人,居然发现大伙对这个都比较陌生,

有的甚至直指EF中是不能调用sqlserver里的方法的。

因为之前搞过linq to sql 里面的SqlMethod ,所以觉得EF里面必须是可以的。

首先需要简短介绍一下EF6和EF5,当你NuGet一个EF5的包的时候,只有EntityFramework,而EF6确有EntityFramework和EntityFramework.SqlServer,

这2者是有很大区别的。

 

在EF5环境下,我们如何使用SqlFunctions 呢?

首先添加EF环境,在引用中添加Syste.Data.Entity,再添加命名空间

<span>using</span> System.Data.Objects.SqlClient;

然后写一个控制器测试

<span> 1</span> <span>public</span><span> ActionResult Index()
</span><span> 2</span> <span>        {
</span><span> 3</span>             <span>int</span> Count = <span>0</span><span>;
</span><span> 4</span>             <span>using</span> (Models.TestProjectDBEntities db = <span>new</span><span> Models.TestProjectDBEntities())
</span><span> 5</span> <span>            {
</span><span> 6</span>                 <span>var</span> Query = <span>from</span> c <span>in</span> db.AdminInfoes <span>where</span> SqlFunctions.Square(<span>1.00</span>)==c.Orders <span>select</span><span> c;
</span><span> 7</span>                 Count =<span> Query.ToList().Count();
</span><span> 8</span> <span>            }
</span><span> 9</span>             ViewBag.Count =<span> Count;
</span><span>10</span>             <span>return</span><span> View();
</span><span>11</span>         }

运行正常。

 

EF6环境下,

我们的引用中是存在EntityFramework和EntityFramework.SqlServer的,

然后我们添加命名空间

<span>using</span> System.Data.Entity.SqlServer;

注意一下,跟EF5下的命名空间是不一样的,这个地方我也是出现了误区,当我的添加是using System.Data.Objects.SqlClient; 的时候一直报错,

这个错误确实比较奇特,我网上找了很多原因一直没有找到,最后一个偶然的机会,才得到这个结果。

然后我们再运行上面的测试代码,应该也是运行通过的。

 

SqlFunctions里提供了很多的方法,这个都是比较简单的,就不做详细介绍了。<br><br>本群提供ASP.NET MVC,EF,LINQ,WEB API技术支持,不在乎人多,在乎人精。<br>ASP.NET MVC群 171560784  <br>诚邀各路高手、初学者加入。

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor