EF 4.1 Code First - Running SQL Queries

EF 4.1 Code First - Running SQL Queries

  • Comments 2

ADO.NET Entity Framework’s Code First 4.1 allows us to execute SQL queries directly. You may need to get one column output or quickly update a table. One thing we need to be careful about running these raw queries is that you need to be double sure about the validity of these…

If you are viewing this article and new to ADO.NET Entity Framework Code First then please visit my blog at http://blogs.msdn.com/b/wriju/archive/2011/04/10/ado-net-entity-framework-code-first-development.aspx

Option 1 If I want to add values to my database,

//Adding data through query
var q1 = db.Database.ExecuteSqlCommand("INSERT INTO Departments(DeptName) Values('Test')");

Option 2 Now want to read data store it already available entity. You need to call .ToList() to trigger the execution.

//Reading data through query
var q2 = db.Depts.SqlQuery("SELECT * FROM Departments").ToList();

Option 3 Want to read data but do not have any entity.

var q3 = db.Database.SqlQuery<string>("SELECT DeptName FROM Departments").ToList();

Namoskar!!!

Leave a Comment
  • Please add 3 and 7 and type the answer here:
  • Post
  • Yes, and even Entity-SQL queries:

    ObjectContext ctx = (db as IObjectContextAdapter).ObjectContext;

    ObjectQuery<Post> q = ctx.CreateQuery<Post>("SELECT VALUE p FROM Post AS p");

    List<Post> posts = q.ToList();

  • For me , Code First replaces Query , I don't want and don't need them 4ever

Page 1 of 1 (2 items)