Friday, September 14, 2012

Entity Framework

What is Entity Framework?

Entity Framework is an additional layer between application and database that enables the developers to program against the conceptual application model instead of programming directly against the relational storage schema.
Will there be any issues adding a table without primary keys to a data model?
Every entity must have a key, even in the case where the entity maps to a view. When you use the Entity Designer to create or update a model, the classes that are generated inherit from EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it to the data model.
How do you truncate a table using entity data model?
Unfortunately Entity Framework doesn't include anything straight forward to handle this. But we can still call a T-SQL statement using entity framework that will still minimizes the developers work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below.

using (var context = new MyTestDbEntities())
{
    context.ExecuteStoreCommand("TRUNCATE table Dummy");
}
How do you query in entity model when the result has a join from from different database other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1
As the entity model doesn't support querying from any entity other than the entities defined in Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the context.
Following code snippet shows how to query when other databases are joined.

string query = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1 = t2.c1";
using (var context = new SampleEntities())
{
  ObjectResult records = context.ExecuteStoreQuery(query);
  foreach (DbDataRecord record in records)
  {
    //Do whatever you want
  }
}

No comments:

Post a Comment