Entity Framework Tutorial Basics(39):Raw SQL Query

Execute Native SQL Query

You can execute native raw SQL query against the database using DBContext. You can execute the following types of queries:

  1. SQL query for entity types which returns particular types of entities
  2. SQL query for non-entity types which returns a primitive data type
  3. Raw SQL commands to the database

SQL query for entity types:

As we have seen in one of the previous chapters, DBSet has SQLQuery() method to write raw SQL queries which return entity instances. The returned objects will be tracked by the context, just as they would be if they were returned by a LINQ query. For example:

using (var ctx = new SchoolDBEntities())
{
    var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>();

}

However, columns returned by SQL query should match the property of an entity type of DBSet otherwise, it will throw an exception. For example:

using (var ctx = new  SchoolDBEntities())
{
    var studentName = ctx.Students.SqlQuery("Select studentid, studentname
        from Student where studentname=‘New Student1‘").ToList();

}

If you change the column name in query, then it will throw an exception because it must match column names:

using (var ctx = new SchoolDBEntities())
{
    //this will throw an exception
    var studentName = ctx.Students.SqlQuery("Select studentid as id, studentname as name
            from Student where studentname=‘New Student1‘").ToList();
}

SQL query for non-entity types:

A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example:

using (var ctx = new SchoolDBEntities())
{
    //Get student name of string type
    string studentName = ctx.Database.SqlQuery<string>("Select studentname
        from Student where studentid=1").FirstOrDefault<string>();
}

Raw SQL commands to the database:

ExecuteSqlCommnad method is useful in sending non-query commands to the database, such as the Insert, Update or Delete command. For example:

using (var ctx = new SchoolDBEntities())
{

    //Update command
    int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student
            set studentname =‘changed student by command‘ where studentid=1");
    //Insert command
    int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname)
            values(‘New Student‘)");
    //Delete command
    int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student
            where studentid=1");

}
时间: 2024-10-16 08:54:45

Entity Framework Tutorial Basics(39):Raw SQL Query的相关文章

Entity Framework Tutorial Basics(1):Introduction

以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx ----------------------------------------------------------------------------------------------------------------------

Entity Framework Tutorial Basics(43):Download Sample Project

Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample project includes SchoolDB.mdf for SQL Server 2012. It also includes SchoolDB.sql script if you are using a different version of SQL Server.

Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet package and in .NET framework. The .NET framework 4.0/4.5 included EF core API, whereas EntityFramework.dll via NuGet package included EF 5.0 specifi

Entity Framework Tutorial Basics(2):What is Entity Framework?

What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Microso

Entity Framework Tutorial Basics(3):Entity Framework Architecture

Entity Framework Architecture The following figure shows the overall architecture of the Entity Framework. Let us now look at the components of the architecture individually: EDM (Entity Data Model): EDM consists of three main parts - Conceptual mode

Entity Framework Tutorial Basics(37):Lazy Loading

Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, Student class contains StudentAddress as a complex property

Entity Framework Tutorial Basics(36):Eager Loading

Eager Loading: Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved using the Include() method. In the following example, it gets all the students from the dat

Entity Framework Tutorial Basics(42):Colored Entity

Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that it would be easy to see related groups of entities in the designer from Visual Studio 2012 onwards. To change the color of an entity, select entity i

Entity Framework Tutorial Basics(41):Multiple Diagrams

Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design time visual representation of the Entity Data Model. This means that you can have multiple diagrams for one Entity Data Model. You can create a new d