Database Reference
In-Depth Information
3-3. Fetching Objects with Native SQL Statements
Problem
You want to execute a native SQL statement and fetch objects from your database.
Solution
Let's say that you have a model with a Student entity type, as shown in Figure 3-4 .
Figure 3-4. A model with a Student entity type
You want to execute a native SQL statement that returns a collection of instances of the Student entity type.
As you saw in the previous recipe, the ExecuteSqlCommand() method is similar to ADO.NET SQLCommand's
ExecuteNonQuery() method. It executes a given SQL statement and returns the number of rows affected. To have
Entity Framework materialize this untyped data into strongly-typed entity objects, we can use the SqlQuery()
method.
To start, this example leverages the Code-First approach for Entity Framework. In Listing 3-5, we create the
Student entity class.
Listing 3-5. Student Entity Class
public class Student
{
public int StudentId { get; set; }
public string Degree { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Next, in Listing 3-6, we create the DbContext object required for our Code-First approach.
Listing 3-6. The DbContext Object
public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("ConnectionString") {}
public DbSet<Student> Students { get; set; }
 
Search WWH ::




Custom Search