Entity Framework Interview questions

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”);


==> 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<DbDataRecord> records = context.ExecuteStoreQuery<DbDataRecord>(query);
foreach (DbDataRecord record in records)
//Do whatever you want


If you don’t have an existing database and dislike visual designers, code first is for you. If you do have an existing database, database first makes sense.

(1) Database First – if you have a pre-existing legacy database (or for some reason you actually want to create the database first) there is a wizard that can create the Entity Data Model based on your choice of tables, views, stored procedures found in the database. You can make various customisations to the model (changing the names of the properties that map to various database columns for example) if necessary.

(2) Model First – if you prefer using visual tools you can create a new Entity Data Model in a designer. This gives you an easy-to-use UI that lets you quickly create new entities, their properties and draw relationships with other entities. Once you’re done the tool can then create a SQL script which will create the database schema upon execution.

(3) Code First – for developers that prefer working in code, you can create your entities by hand. At runtime EF will build an in-memory model the runtime can work with.



What is .edmx file and what it contains?
An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

What do you mean by Navigation Property?
A property of an entity type that represents a relationship to another entity type, as defined by an association. Navigation properties are used to return related objects as an EntityCollection or an EntityReference, depending on the multiplicity at the other end of the association.

Code First: Start with Code and Forego a Physical Model

With Database First and Model First, you’ll end up with a physical representation of your EDM along with additional metadata. The raw format of this model is XML. It’s stored in a file with an EDMX extension, and you can work with it in the EDM Designer or the raw XML. At run time, the Entity Framework reads that XML and creates an in-memory representation of the model using specialized classes that represent the metadata—entities, relationships and so on. The Entity Framework runtime works with those objects, not the actual XML file. This metadata is especially critical when the Entity Framework needs to transform model queries into database queries, database results into entity instances, and create database commands for inserts, updates and deletes. Visual Studio will generate your domain classes from the XML to use in your application.

The Entity Framework team has come up with a way to create the needed metadata objects at run time without requiring you to have a physical EDMX file. This is the power behind the third model-creation workflow for the Entity Framework, called Code First. With Code First, rather than creating an EDM, you create your domain classes as you would for any other .NET development. At run time, the Entity Framework will inspect those classes and, using a set of default conventions, build an in-memory model that the Entity Framework runtime can work with. Because your classes won’t always naturally provide the information that the Entity Framework needs to create that model, you can provide additional configuration (using declarative attributes/data annotations or in code using a fluent API) to further describe the model, overriding the conventions mentioned earlier. You can use configuration for a wide variety of model tasks, from identifying primary keys that don’t match Code First conventions to fine-tuning relationships or even specifying how an inheritance hierarchy should be represented.

Like Model First, Code First defaults to the presumption that you aren’t starting with a legacy database, and provides the capability to create that database from the inferred model. Unlike Model First, you can create the database file as well as the schema. With Code First, you still lack a way to persist database data if you modify the model and regenerate the database. However, Code First does have support to detect model and database differences, as well as seed the database with data using database initializers.

You can also use Code First with an existing database. If your class and property names don’t match up to the database, you can add data annotations or configuration through the fluent API to overcome that.Figure 3 shows a class with attributes that will force Code First to provide mappings to the correct table and property names even though the class and fields don’t match exactly.

Figure 3 A Class with Code First Attributes to Ensure the Class Can Correctly Map to an Existing Table

  1. [Table(“SalesOrderDetail”, SchemaName=”SalesLT”)]
  2.   public partial class Detail
  3.   {
  4.     // Scalar properties
  5.     [Column(Name = “SalesOrderID”)]
  6.     public int OrderId { get; set; }
  7.     [Column(Name = “SalesOrderDetailID”)]
  8.     public int DetailId { get; set; }
  9.     public short OrderQty { get; set; }
  10.     public int ProductId { get; set; }
  11.     public decimal UnitPrice { get; set; }
  12.     public decimal UnitPriceDiscount { get; set; }
  13.     public decimal LineTotal { get; set; }
  14.     public System.DateTime ModifiedDate { get; set; }
  15.     // Navigation properties
  16.     public virtual Product Product { get; set; }
  17.     public virtual Order Order { get; set; }
  18.   }


CRUD operations without mapping the Stored Procedures to the model.

entities.ExecuteStoreCommand("InsertEmployee @ID,@EmpName,@EmpAddress", 
                          ietsParameterID, ietsParameterEmpName, ietsParameterEmpAddress);


var selectData = entities.ExecuteStoreQuery<Employee>("SelectEmployee").ToList();



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s