Entity Framework IQ’s
Contents
What is Entity Framework?
ADO.NET
entity is an ORM (object relational mapping) which creates a higher abstract
object model over ADO.NET components. So rather than getting into dataset,
datatables, command, and connection objects as shown in the below code, you
work on higher level domain objects like customers, suppliers, etc.
DataTable table = adoDs.Tables[0];
for (int j = 0; j < table.Rows.Count; j++)
{
DataRow row = table.Rows[j];
// Get the values of the
fields
string CustomerName =
(string)row["Customername"];
string CustomerCode =
(string)row["CustomerCode"];
}
Below is the
code for Entity Framework in which we are working on higher level domain
objects like customer rather than with base level ADO.NET components (like
dataset, datareader, command, connection objects, etc.).
foreach (Customer objCust in obj.Customers)
{}
What are the
benefits of using EF?
The main and
the only benefit of EF is it auto-generates code for the Model (middle layer),
Data Access Layer, and mapping code, thus reducing a lot of development time.
What
are the different ways of creating these domain / entity objects?
Entity
objects can be created in two ways: from a database structure, or by starting
from scratch by creating a model.
What
is pluralize and singularize in the Entity Framework dialog box?
“Pluralize”
and “Singularize” give meaningful naming conventions to objects. In simple
words it says do you want to represent your objects with the below naming
convention:
·
One Customer record means “Customer”
(singular).
·
Lot of customer records means
“Customer’s” (plural, watch the “s”)
If you select
the below checkbox, Entity Framework generates a naming convention which
adheres to plural and singular coding conventions.
What
is the importance of EDMX file in Entity Framework?
EDMX (Entity
Data Model XML) is an XML file which contains all the mapping details of how
your objects map with SQL tables. The EDMX file is further divided into three
sections: CSDL, SSDL, and MSL.
Can
you explain CSDL, SSDL and MSL sections in an EDMX file?
·
CSDL (Conceptual Schema definition
language) is the conceptual abstraction which is exposed to the application.
·
SSDL (Storage Schema Definition
Language) defines the mapping with your RDBMS data structure.
·
MSL (Mapping Schema Language)
connects the CSDL and SSDL.
CSDL, SSDL
and MSL are actually XML files.
Figure: CSDL, MSL, and SSDL
T4 (Text
Template Transformation Toolkit) is a template based code generation engine.
You can go and write C# code in T4 templates (.tt is the extension)
files and those C# codes execute to generate the file as per the written C#
logic.
For
instance, the below T4 C# code:
<#@ template language="“C#”" #>
Hello <# Write(”World!”) #>
Will
generate the following C# output:
What
is the importance of T4 in Entity Framework?
T4 files are
the heart of EF code generation. The T4 code templates read the EDMX XML file
and generate C# behind code. This C# behind code is nothing but your entity and
context classes.
If you
create a project using VS 2012, you will see the following hierarchy. At the
top we have the EDMX file, followed by the TT or T4 file, and then the .CS code
file.
How
can we read records using Entity Framework classes?
In order to
browse through records you can create the object of the context class and
inside the context class you will get the records.
For
instance, in the below code snippet we are looping through a customer object
collection. This customer collection is the output given by the context class CustomermytextEntities.
CustomermytestEntities obj = new CustomermytestEntities();
foreach (Customer objCust in obj.Customers)
{}
How
can we add, update, and delete using EF?
Create the
object of your entity class, add it to the data context using AddObject method, and then call theSaveChanges method.
CustomermytestEntities obj = new CustomermytestEntities();
Customer objCust = new Customer();
objCust.CustomerCode = "1001";
obj.Customers.AddObject(objCust);
obj.SaveChanges();
If you want
to update, select the object, make changes to the object, and call AcceptAllChanges.
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges();
If you want
to delete, call the DeleteObject method as shown in the below code snippet:
CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objContext.DeleteObject(objCustomer);
You can see
the following YouTube video which shows a simple insert, update, and delete
example using Entity Framework:
People
say Entity Framework runs slow
By default
EF has lazy loading behavior. Due to this default behavior if you are loading a
large number of records and especially if they have foreign key relationships,
you can have performance issues. So you need to be cautious if you really need
lazy loading behavior for all scenarios. For better performance, disable lazy
loading when you are loading a large number of records or use stored procedures.
Can
you explain lazy loading in a detailed manner?
Lazy loading
is a concept where we load objects on demand rather than loading everything in
one go. Consider a situation where you have 1 to many relationships between the
Customer and Address objects. Now let’s say you are browsing the customer data
but you do not want address data to be loaded at that moment. But the time you
start accessing the address object you would like to load address data from the
database.
Entity
Framework has lazy loading behavior by default enabled. For instance, consider
the below code. When we are doing a foreach on the Customer object, the Address object is not
loaded. But the time you start doing foreach on the address collection, the Address object is
loaded from SQL Server by firing SQL queries.
So in simple
words, it will fire a separate query for each address record of the customer,
which is definitely not good for a large number of records.
MyEntities context = new MyEntities();
var Customers = context.Customers.ToList();
foreach (Customercust in Customers) // In this line no address object
loaded
{
foreach(Address add in
cust.Addresses){}// Address object is loaded here
}
How can we
turn off lazy loading?
The opposite
of lazy loading is eager loading. In eager loading we load the objects
beforehand. So the first thing is we need to disable lazy loading by setting LazyLoadingEnabled to false.
context.ContextOptions.LazyLoadingEnabled = false;
Now we have
to explicitly tell EF what objects we want to load by using the include function. Below is a simple sample code where we tell
EF to load customer as well as address objects by using the include function.
Now the
customer object and the related address objects will be loaded in one query
rather than multiple queries.
var employees = context.Customers.Include("Addresses").Take(5);
How
can we use stored procedures in Entity Framework?
You can use
stored procedure mapping details in EDMX as shown in the below figure.
Figure: Specify stored procedures
What
are POCO classes in Entity Framework?
POCO means
Plain Old C# Object. When EDMX creates classes, they are cluttered with a lot
of entity tags. For instance, below is a simple customer class generated using
Entity Framework. Many times we would like to use simple .NET classes and
integrate them with Entity Framework.
Entity
Framework allows this. In other words you can create a simple .NET class and
use the entity context object to load your simple .NET classes.
Below is a
simple class generated by EF which is cluttered with a lot of EF attributes.
[EdmEntityTypeAttribute(NamespaceName="CustomermytestModel",
Name="Customer")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Customer : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Customer
object.
/// </summary>
/// <param name="id"
/>Initial value of the Id property.
/// <param name="customerCode"
/>Initial value of the CustomerCode property.
/// <param name="customername"
/>Initial value of the Customername property.
public static Customer
CreateCustomer(global::System.Int32 id,
global::System.String
customerCode, global::System.String customername)
{
Customer customer = new Customer();
customer.Id = id;
customer.CustomerCode =
customerCode;
customer.Customername =
customername;
return customer;
}
#endregion
#region Primitive Properties
How
do we implement POCO in Entity Framework?
To implement
POCO is a three step process:
·
Go to the designer and set the code
generation strategy to NONE. This step means that you would be generating the classes
on your own rather than relying on EF auto code generation.
·
Now that we have stopped the auto
generation of code, we need to create the domain classes manually. Add a class
file and create the domain classes like the Customer class we created.
public class Customer
{
private string _customerName;
public string CustomerName
{
get { return _customerName; }
set { _customerName = value;
}
}
private int _Customerid;
public int Customerid
{
get { return _Customerid; }
set { _Customerid = value; }
}
}
·
Write your Context layer code
inheriting from ObjectContext. This code you can copy paste from the behind code of EF,
also before disabling auto-generation.
public partial class Test123Entities : ObjectContext
{
public Test123Entities()
: base("name=Test123Entities",
"Test123Entities")
{
this.ContextOptions.LazyLoadingEnabled
= true;
OnContextCreated();
}
partial void OnContextCreated();
public ObjectSet<Customer> Customers
{
get
{
if ((_Customers == null))
{
_Customers = base.CreateObjectSet<Customer>("Customers");
}
return _Customers;
}
}
private ObjectSet<Customer> _Customers;
public void
AddToCustomers(Customer customer)
{
base.AddObject("Customers",
customer);
}
}
And finally
you can use the above code in your client as if you where using EF normally.
Test123Entities oContext = new Test123Entities();
List<Customer> oCustomers =
oContext.Customers.ToList<Customer>();
In
POCO classes do we need EDMX files?
Yes, you
will still need EDMX files because the context object reads the EDMX files to
do the mapping.
What
is Code First approach in Entity Framework?
In Code
First approach we avoid working with the Visual Designer of Entity Framework.
In other words the EDMX file is excluded from the solution. So you now have
complete control over the context class as well as the entity classes.
What
is the difference between POCO, Code First, and simple EF approach?
All these
three approaches define how much control you want on your Entity Framework
code. Entity Framework is an OR mapper, it generates a lot of code, it creates
your middle tier (Entity), and Data Access layer (Context).
But a lot of
times you want to enjoy the benefits of both worlds, you want the
auto-generation part to minimize your development time and you want control on
the code so that you can maintain code quality.
Below is the
difference table which defines each of the approaches. In simple Entity
Framework, everything is auto generated and so you need the EDMX XML file as
well. POCO is semi-automatic so you have full control on the entity classes but
then the context classes are still generated by the EDMX file.
In Code
First, you have complete control on how you can create the entity and context
classes. Because you are going to manually create these classes, you do not
have dependency on the EDMX XML file. Below is a simple table which shows the
cross comparison.
|
EDMX
|
Entity
|
Context
|
|
Simple entity framework
|
Needed
|
Auto
|
Auto
|
|
POCO approach
|
Needed
|
Manual
|
Auto
|
|
Code First
|
Not Needed
|
Manual
|
Manual
|
How
can we handle concurrency in Entity Framework?
Note: Before this question, the interviewer can ask you about
concurrency and what is pessimistic and optimistic locking. Please do refer to
the ADO.NET chapter for those.
In EF,
concurrency issue is resolved by using optimistic locking. Please refer to the
ADO.NET chapter for what is optimistic locking and pessimistic locking? To
implement optimistic locking, right click on the EDMX designer and set the
concurrency mode to Fixed,
as shown in the below figure.
Now whenever
we have concurrency issues you should get an OptimisticConcurrencyException error as shown in the below figure. You can then put a try
/ catch to handle this situation.
How
can we do pessimistic locking in Entity Framework?
We cannot do
pessimistic locking using Entity Framework. You can invoke a stored procedure
from Entity Framework and do pessimistic locking by setting the isolation level
in the stored procedure. But directly, Entity Framework does not support
pessimistic locking.
What
is client wins and store wins mode in Entity Framework concurrency?
Client wins
and store wins are actions which you would like to take when concurrency
happens. In store wins / database wins, the data from the server is loaded into
your entity objects. Client wins is opposite to stored wins, data from the
entity object is saved to the database.
We need to
use the Refresh method of the Entity Framework context and provide the RefreshMode enum values. Below is a simple code snippet which
executes ClientWins.
Context.Refresh(System.Data.Objects.RefreshMode.ClientWins,Obj);
What
are scalar and navigation properties in Entity Framework?
Scalar
properties are those where actual values are contained in the entities. For
example, in the above customer entity, customername and customerid are scalar properties. Normally a scalar property will
map to a database field.
Navigation
properties help to navigate from one entity to another entity. For instance,
consider the below example in which we have two entities: Customer and Address,
and a customer has multiple address objects.
Now we would
like to have a facility where at any given moment we would like to browse from
a given customer object to the addresses collection and from the address object
to the customer.
If you open
the Entity Designer, you would notice navigation properties as shown below. The
navigation properties are automatically created from the primary and foreign
key references.
So now
because of those navigation properties, we can browse from the Customer to the Addresses object, look at the below code:
Customer Cust =
oContext.Customers.ToList<Customer>()[0];
// From customer are browsing addresses
List<Address> Addresses = Cust.Addresses.ToList<Address>();
You can also
do vice versa. In other words, from the Address object, you can reference the Customer object, as shown in the below code.
Address myAddress = Addresses[0];
// From address we can browse customer
Customer cus = myAddress.Customer;
What
are complex types in Entity Framework?
There can be
situations where you have common properties across entities. For example,
consider the below figure where we have Customer and Supplier entities. They have three fields in common: Address1, Address2, andPhoneNo. These fields have been duplicated both in the Customer and Supplier entities.
So to remove
these duplicate and redundant fields, we can move them to a common complex type
called Address. Complex types group common fields so that they can be
reused across entities.
To create a
complex type, select the fields which you want to group in a complex type,
click on Refactor, and create the complex type. Below is a figure which shows
this. Once the complex type is created, you can then reuse the complex type
with other entities as well.
What’s
the difference between LINQ to SQL and Entity Framework?
·
LINQ to SQL is good for rapid
development with SQL Server. EF is for enterprise scenarios and works with SQL
Server as well as other databases.
·
LINQ maps directly to tables. One
LINQ entity class maps to one table. EF has a conceptual model and that
conceptual model maps to the storage model via mappings. So one EF class can
map to multiple tables, or one table can map to multiple classes.
·
LINQ is more targeted towards rapid
development while EF is for enterprise level where the need is to develop a
loosely coupled framework.
What
is the difference between DbContext and ObjectContext?
DbContext is a wrapper around ObjectContext, it’s a simplified version of ObjectContext.
As a
developer you can start with DbContext as it’s simple to use. When you feel that some of the
operations cannot be achieved by DbContext, you can then access ObjectContext from DbContext, as shown in the below code:
((IObjectContextAdapter)dbContext).ObjectContext
Note: If the interviewer asks what kind of operations are not
supported in DbContext, you can excuse by saying you do not remember them up
front. Wonder why sometimes interviewers ask API level questions?
28 ADO.Net
Entity Framework Questions and Answers:
1 :: What is
Entity Framework?
The
Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM)
framework that enables developers to work with relational data as
domain-specific objects, eliminating the need for most of the data access
plumbing code that developers usually need to write. Using the Entity
Framework, developers issue queries using LINQ, then retrieve and manipulate
data as strongly typed objects. The Entity Framework’s ORM implementation
provides services like change tracking, identity resolution, lazy loading, and
query translation so that developers can focus on their application-specific
business logic rather than the data access fundamentals.
To simply
say it: Entity framework is an Object/Relational Mapping (O/RM) framework. It
is an enhancement to ADO.NET that gives developers an automated mechanism for
accessing & storing the data in the database and working with the results
in addition to DataReader and DataSet.
Now the
question is what is O/RM framework and why do we need it?
ORM is a
tool for storing data from domain objects to relational database like MS SQL
Server in an automated way without much programming. O/RM includes three main
parts: Domain class objects, Relational database objects and Mapping
information on how domain objects maps to relational database objects (tables,
views & storedprocedures). ORM helps us to keep our database design
separate from our domain class design. This makes application maintainable and
extendable. It also automates standard CRUD operation (Create, Read, Update
& Delete) so developer doesn’t need to write it manually.
Is This
Answer Correct?38 Yes 1 No
Post Your
Answer
2 :: What
are differences between Entity Framework and L2S?
Entity
framework has a full provider model. It supports not only SQL Server but also
other database like Oracle, DB2, MySQL etc.
Most of the
time L2S classes must be one-to-one with database objects e.g. Customer class
can be mapped only with Customer table. Where as in Entity Framework you can
map your domain class with multiple tables using various inheritance strategies
like table per type (class) or table per hierarchy of classes etc.
You can have
multiple modeling techniques using Entity Framework 4.1 like code first, model
first or database first.
Microsoft has
long term strategy to support and integrate Entity Framework with multiple
Microsoft products.
Is This
Answer Correct?33 Yes 2 No
Post Your
Answer
3 :: What is
EDM (Entity Data Model)?
EDM consist
three main parts- Conceptual model, Mapping and Storage model.
Is This
Answer Correct?45 Yes 5 No
Post Your
Answer
4 :: What is
Conceptual Model?
Conceptual
model is your model classes and their relationships. This will be independent
from your database table design.
Is This
Answer Correct?38 Yes 2 No
Post Your
Answer
5 :: What is
Storage Model?
Storage
model is your database design model which includes tables, views, stored
procedures and their relationships and keys.
Is This
Answer Correct?34 Yes 3 No
Post Your
Answer
6 :: What is
Mapping in Entity Framework?
Mapping
consist information about how your conceptual model is mapped to storage model.
Is This
Answer Correct?32 Yes 0 No
Post Your
Answer
7 :: Explain
LINQ to Entities?
LINQ to
Entities is query language used to write queries against the object model. It
returns entities which are defined in the conceptual model. You can use your
LINQ skills here.
Is This
Answer Correct?24 Yes 1 No
Post Your
Answer
8 :: What is
Entity SQL?
Entity SQL
is again a query language same as LINQ to Entities. However it is little more
difficult than L2E and also developer need to learn it separately.
9 :: What is
Object Service?
Object
service is a main entry point for accessing data from database and to return it
back. Object service is responsible for materialization which is process of
converting data returned from entity client data provider (next layer) to an
entity object structure.
10 :: What
is Entity Client Data Provider?
The main
responsibility of this layer is to convert L2E or Entity SQL queries into SQL
query which is understood by underlying database. It communicates with ADO.Net
data provider which in turn sends or retrieves data from database.
11 :: What
is ADO.Net Data Provider?
This layer
communicates with database using standard ADO.Net.
12 :: What
is EDM Designer?
EDM designer
represents your conceptual model. It consists Entities, associations &
multiplicity between the entities. Initially it will exactly look like your
database table structure but you can add or merge columns or remove columns
which are not required by your application from this designer. Even you can add
new object in this model which can have columns from different database tables
from context menu as shown in above figure. Remember, whatever changes you do
here it should be mapped with storage model. So you have to be careful while
doing any changes in the designer.
13 :: What
is EntityContainer?
EntityContainer
is a wrapper for EntitySets and AssociationSets. It is critical entry point for
querying the model.
14 :: What
is EntitySet?
EntitySet is
a container for EntityType. It is set of same entitytype. You can think it like
db table.
15 :: What
is EntityType?
EntityType
is a datatype in the model. You can see each EntityType for your conceptual
model in XML. If you expand EntityType node in XML, you can see each properties
and its type and other info.
16 :: What
is AssociationSet?
AssociationSet
defines the relation between each EntitySet.
17 :: What
is ObjectContext?
Now, if you
open designer.cs, you can see two main regions, Contexts and Entities. Expand
contexts region. You can see partial class with suffix ‘entities’ and derived
from ObjectContext class.
18 :: What
is ObjectSet?
Each
EntitySet in context class is a type of ObjectSet<> that wraps the
entity. e.g. ObjectSet.
19 :: What
is IObjectSet?
IObjectSet
is a interface which gives collection like functionality. ObjectSet<>
also implements IObjectSet. IObjectSet is useful in unit testing where you can
create fake EntitySet (of type IObjectSet<>). We have used IObjectSet in
our sample project.
20 :: What
is EntityTypes?
Now if you
expand ‘Entities’ region, you can see many partial classes that are derived
from EntityObject. This classes are EntityTypes of you model.
21 :: What
is POCO Proxy?
POCO Proxy
is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity
if it meets certain requirements to enable lazy loading proxy and instant
change tracking. It adds some methods at runtime to your POCO class which does
instant change tracking and lazy loading stuff.
POCO entity
should meet the following requirement to become POCO proxy:
A custom
data class must be declared with public access.
A custom
data class must not be sealed (NotInheritable in Visual Basic)
A custom
data class must not be abstract (MustInherit in Visual Basic).
A custom
data class must have a public or protected constructor that does not have
parameters.
The class
cannot implement the IEntityWithChangeTracker or IEntityWithRelationships
interfaces because the proxy classes implement these interfaces.
The
ProxyCreationEnabled option must be set to true.
Each
navigation property must be declared as public, virtual
22 :: What
is Code First?
In Code
First approach, you avoid working with visual model designer (EDMX) completely.
You write your POCO classes first and then create database from these POCO
classes. Developers who follow the path of Domain-Driven Design (DDD)
principles prefer to begin by coding their classes first and then generating
the database required to persist their data.
23 :: What
is Model First?
In Model
First approach, you create Entities, relationships, and inheritance hierarchies
directly on the design surface of EDMX. So in Model First approach, when you
add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of
‘Generate from database’.
24 :: Explain
Entity Lifecycle?
During
entity’s lifetime, each entity has an entity state based on operation performed
on it via Context (ObjectContext). The entity state is an enum of type
System.Data.EntityState that declares the following values:
Added
Deleted
Modified
Unchanged
Detached
25 :: What
is Connected Scenario?
Connected
scenario is when an entity is retrieved from the database and modified in the
same context.
26 :: What
is Disconnected Scenario?
Disconnected
scenario is when an entity is retrieved from the database and modified in the
different context. Disconnected scenario is complex because context doesn’t
know anything about modified entity so you have to tell to ObjectContext that
what has changed in entity.
27 :: What
is Entity Graph?
When an
entity has relation with other entities then it called entity graph because
more entities are involved, for example Student entity graph includes many
other entities like Standard, StudentAddress & Course.
28 :: What
is DefiningQuery in Entity Framework?
A defining
query allows you to execute a native SQL statement that is specified in the
DefiningQuery element in the EntitySet element in the SSDL.
A defining
query is commonly used to provide functionality similar to that provided by a
database view, but this native SQL statement will be in the .edmx file, not in
the database. The entityset in CSDL is used to surface data exposed by the
defining query.
So here, we
will see how we can execute same SQL using DifiningQuery which we used in
database view in previous chapter and get the same functionality as database
view.
We will
perform following three steps to create and use DefiningQuery:
Add
DefiningQuery in SSDL
Add
EntitySet in CSDL
Mapping
between Conceptual and Storage EntitySets
Version History
The first two versions of Entity Framework shipped with the .NET
Framework and had versions numbers that aligned with the version of the
framework that they were included in (3.5 and 4). After this EF started
shipping independently and adopted the http://semver.org standard for semantic
versioning.
Here is a
summary of the Entity Framework releases and the features they added. This
table includes all the fully supported releases of Entity Framework and the
latest pre-release version.
|
Release
|
Summary
|
|
EF
6.1
|
This minor release
adds the following features to EF6:
·
IndexAttributeallows indexes to
be specified by placing an [Index] attribute on a property (or properties) in
your Code First model. Code First will then create a corresponding index in
the database.
·
The public mapping API provides
access to the information EF has on how properties and types are mapped to
columns and tables in the database. In past releases this API was internal.
·
Migrations model change detection has been
improved so that scaffolded migrations are more accurate; performance of the
change detection process has also been enhanced.
·
Performance improvements including reduced database
operations during initialization, optimizations for null equality comparison
in LINQ queries, faster view generation (model creation) in more scenarios,
and more efficient materialization of tracked entities with multiple
associations.
|
|
|
|
|
EF
6.0.2
|
The 6.0.2 patch
release is limited to fixing issues that were introduced in the EF6 release
(regressions in performance/behavior since EF5).
|
|
|
|
|
EF
6.0.1
|
The
6.0.1 patch release is limited to fixing issues that were introduced in the
EF6 release (regressions in performance/behavior since EF5). This is a
runtime only release ( available
on NuGet), there was no update to the tooling.
The most notable
changes were to fix some performance issues during warm-up for EF models.
This was important as warm-up performance was an area of focus in EF6 and
these issues were negating some of the performance gains made in EF6.
|
|
|
|
|
EF
6
|
This release can be
used in Visual Studio 2013, Visual Studio 2012 and Visual Studio 2010
(runtime only) to write applications that target .NET 4.0 and .NET 4.5.
Tooling
The
EF6 Tooling is included in Visual Studio 2013 and available for download for
Visual Studio 2012. See the Get Entity Framework page for more information.
The focus for the
tooling in EF6 was to add support for the EF6 runtime and to enable shipping
out-of-band between releases of Visual Studio.
The tooling itself
does not include any new features, but most of the new runtime features can
be used with models created in the EF Designer.
Runtime
The
EF6 runtime can be installed from NuGet. See the Get Entity Framework page for more information.
The following
features work for models created with Code First or the EF Designer:
·
Async Query and Save adds support
for the task-based asynchronous patterns that were introduced in .NET 4.5.
·
Code-Based Configuration gives you the
option of performing configuration – that was traditionally performed in a
config file – in code.
·
Dependency Resolution introduces
support for the Service Locator pattern and we've factored out some pieces of
functionality that can be replaced with custom implementations.
·
Interception/SQL logging provides
low-level building blocks for interception of EF operations with simple SQL
logging built on top.
·
Improved Transaction Support provides
support for a transaction external to the framework as well as improved ways
of creating a transaction within the Framework.
·
Enums, Spatial and Better Performance on .NET 4.0 - By moving
the core components that used to be in the .NET Framework into the EF NuGet
package we are now able to offer enum support, spatial data types and the
performance improvements from EF5 on .NET 4.0.
·
Improved performance of Enumerable.Contains in LINQ queries.
·
Improved warm up time (view generation), especially for large
models.
·
Pluggable Pluralization & Singularization Service.
·
Custom implementations of Equals or GetHashCode on entity
classes are now supported.
·
DbSet.AddRange/RemoveRange provides an optimized way to
add or remove multiple entities from a set.
·
DbChangeTracker.HasChanges provides an easy and efficient
way to see if there are any pending changes to be saved to the database.
·
SqlCeFunctions provides a SQL Compact
equivalent to the SqlFunctions.
The following
features apply to Code First only:
·
Custom Code First Conventions allow write
your own conventions to help avoid repetitive configuration. We provide a
simple API for lightweight conventions as well as some more complex building
blocks to allow you to author more complicated conventions.
·
Configurable Migrations History Table allows you to
customize the definition of the migrations history table. This is
particularly useful for database providers that require the appropriate data
types etc. to be specified for the Migrations History table to work
correctly.
·
Multiple Contexts per Database removes the previous limitation
of one Code First model per database when using Migrations or when Code First
automatically created the database for you.
·
DbModelBuilder.HasDefaultSchema is a new Code
First API that allows the default database schema for a Code First model to
be configured in one place. Previously the Code First default schema was
hard-coded to "dbo" and the only way to configure the schema to
which a table belonged was via the ToTable API.
·
DbModelBuilder.Configurations.AddFromAssembly method allows you to
easily add all configuration classes defined in an assembly when you are
using configuration classes with the Code First Fluent API.
·
Default transaction isolation level is changed to
READ_COMMITTED_SNAPSHOT for databases created using Code First, allowing for
more scalability and fewer deadlocks.
·
Entity and complex types can now be nestedinside classes.
|
|
|
|
|
EF
5
|
This release can be
used in Visual Studio 2010 and Visual Studio 2012 to write applications that
target .NET 4.0 and .NET 4.5. When targeting .NET 4.5 this release introduces
some new features including enum support, table-valued functions, spatial
data types and various performance improvements.
If you create a new
model using the Entity Framework Designer in Visual Studio 2012, the EF5
NuGet package will be installed to your project and the generated code will
make use of EF5. New ASP.NET projects created in Visual Studio 2012
(including MVC projects) also have the EF5 NuGet package installed by
default.
The Entity
Framework Designer in Visual Studio 2012 also introduces support for
multiple-diagrams per model, coloring of shapes on the design surface and
batch import of stored procedures.
|
|
|
|
|
EF
4.3.1
|
This
patch release included some bug fixes to the EF 4.3 release and introduced
better LocalDb support for folks using EF 4.3 with Visual Studio 2012.
|
|
|
|
|
EF
4.3
|
The
EF 4.3 release included the new Code First Migrations feature that allows a
database created by Code First to be incrementally changed as your Code First
model evolves.
|
|
|
|
|
EF
4.2
|
This release
includes bug fixes to the EF 4.1.1 release.
Because
this release only included bug fixes it could have been the EF 4.1.2 patch
release but we opted to move to 4.2 to allow us to move away from the date
based patch version numbers we used in the 4.1.x releases and adopt the http://semver.org standard
for semantic versioning.
|
|
|
|
|
EF
4.1.1
|
In addition to bug
fixes this patch release introduced some components to make it easier for
design time tooling to work with a Code First model. These components are
used by Code First Migrations (included in EF 4.3) and the EF Power Tools.
Note
the NuGet package for this release has the version number 4.1.10715. We used
to use date based patch versions before we decided to adopt the http://semver.org standard
for semantic versioning.
|
|
|
|
|
EF
4.1
|
The EF 4.1 release
was the first to be published on NuGet. This release included the simplified
DbContext API and the Code First workflow.
Note
the NuGet package for this release has the version number 4.1.10331. We used
to use date based patch versions before we decided to adopt the http://semver.org standard
for semantic versioning.
|
|
|
|
|
EF
4
|
This release was
included in .NET Framework 4 and Visual Studio 2010. New features in this
release included POCO support, lazy loading, testability improvements,
customizable code generation and the Model First workflow.
Although it was the
second release of Entity Framework it was named EF 4 to align with the .NET
Framework version that it shipped with. After this release we started making
Entity Framework available on NuGet and adopted semantic versioning since we
were no longer tied to the .NET Framework Version.
|
|
|
|
|
EF
(or EF 3.5)
|
The
initial release of Entity Framework was included in .NET 3.5 SP1 and Visual
Studio 2008 SP1. This release provided basic O/RM support using the Database
First workflow.
|
O.NET Entity Framework is an Object/Relational
Mapping (ORM) framework that enables developers to work with various relational
databases like SQL Server, Oracle, DB2, MYSQL etc. It enables developers to
deal with data as business objects and entities. Using the Entity Framework,
developers issue queries using LINQ, then retrieve and manipulate data as
strongly typed objects using C# or VB.NET.
ADO.NET Entity Framework Version History
ADO.NET Entity Framework Version
Supported Framework & IDE
Features Detail
6.0
.NET Framework 4.5.1 and Visual Studio 2013
1.
Async Query and Save
2.
Code-Based
Configuration
3.
Dependency Resolution
4.
Interception/SQL
logging
5.
Improved Connection
Management
6.
Improved Transaction
Support
5.0
.NET Framework 4.5 and Visual Studio 2012
1.
Enum Support in Code
First and EF Designer
2.
Spatial Data Types in
Code First and EF Designer
3.
Table-Valued Functions
4.
Multiple Diagrams per
Model
4.3
.NET Framework 4.0 and Visual Studio 2010
1.
Code First Migrations
2.
Automatic Migrations
4.2
.NET Framework 4.0 and Visual Studio 2010
1.
The EF 4.2 release
included the bug fixes to EF 4.1
4.1
.NET Framework 4.0 and Visual Studio 2010
1.
Code First development
2.
Introduced DbContext
API
3.
Data Annotations and
Fluent API Validation
4.0
.NET Framework 4.0 and Visual Studio 2010
1.
Model-first
development
2.
POCO support
3.
Lazy Loading
4.
T4 Code Generation
3.5
.NET Framework 3.5 SP1 and Visual Studio 2008 SP1
1. This release provided basic O/RM support using
the Database first development
1)
What is “code first” in relation to Entity framework?
Entity
framework uses the process of “code first” that maps database tables to data
models. The data models in your .NET project are actually classes that
represent the structure of your database tables. This code is used to work with
your database, so you don’t need a direct connection to your database in each
of your class methods.
2) What is the difference between old ADO .NET and Entity
framework coding techniques?
When
you used ADO, you connected to the database and had to define a stored
procedure or query to retrieve data. With Entity framework, you don’t have to
be “blind” when it comes to your tables. ADO did not allow you to get the table
structure. With code first, you already have the table structure and Entity
framework connects to the database and hides any connection processes. With
Entity framework, you’re more aware of the database structure, which helps you
avoid any coding mistakes. In addition, if the table structures change, Entity
framework updates the data models for you during a refresh.
3) What is LINQ?
Language-Integrated
Query (LINQ) is a way to query data without cumbersome stored procedures.
Previously, programmers needed to create stored procedures and then call these
stored procedures from their code. With Entity framework, you can pull data and
query it using language similar to SQL.
4) How is data retrieved?
The
difference between older retrieval methods and current Entity framework
retrieval methods is that you can now (with Entity) retrieve data as objects.
The objects represent the tables (or linked tables) in your database. Instead
of iterating through several columns and rows, you just use your class data
models. For instance, if you have a table named “users,” you can use the
“users” class instead of working through each data set after your query.
5) Can you run SQL statements in an Entity framework environment?
Yes,
you can also run SQL query statements. You can use the “ExecuteStoreCommand”
method to run SQL on your database. This is usually a secondary option from
running simple LINQ on your Entity framework code. You can also run stored
procedures from a database.
6) How do you create a database model?
Visual
Studio has a database modeler available. You can create a database model from
scratch, or you can query the database for the models. If you have a database
already, you simply pull the database structures from your code and Entity
framework will automatically set up the class data models.
7) Does Entity framework support primary and foreign keys?
Yes,
Entity framework supports both types of primary and foreign keys. You can
define these in your database tables and import them to your model classes. If
you don’t already have a database set up, you can create these keys in your
data model classes and their respective data modeling classes.
8) How do you mark a data column as required by the database?
You
can “decorate” your data models. The “Required” decoration marks a field as
required. Before a user can submit the data to the database, the user must have
this field entered. You can also auto-generate required fields in your code, so
the code automatically adds the required data.
9) What is lazy loading?
Lazy
loading is a way to return only objects that are used. When you query the
database model, lazy loading only returns the immediate tables needed by the
user. All related tables are returned when they are used. This means you can
reserve memory and storage when you work with large programs. It also means
that objects are created until you need them, so it makes your program faster.
10) What is eager loading?
Eager
loading is the opposite of lazy loading. When you query for objects, eager
loading returns all of the objects including the related objects. For instance,
when you query a list of customers and orders, eager loading loads all objects
including the customers and the orders instead of just what you originally need
(customers).
11) What is a navigation property?
A
navigation property points to related tables in your database model. For
instance, if you have a customer table that relates to the orders table, the
navigation property points from the customers table to the orders table. While
the primary and foreign keys are physical properties of the table, the
navigation properties are a logical part of a data model. When you view the
Entity framework model, you can view the navigation properties to better
understand the structure of your tables.
12) What is a scalar property in your data model?
A
scalar property is similar to a scalar property in the database. A scalar
property points to one location in the table.
13) What is a complex data type?
A
complex data type occurs when you need to point to another data object from one
data object. For instance, if you have several tables that require an address,
you can turn those addresses into a table of addresses. You then point your
address columns to the new address table, which creates a complex data type.
You will likely have complex data types in every .NET Entity framework project,
because it makes it easier to relate one table and data model to another
without creating cumbersome code.
14) Overall, what is Entity framework?
Entity
framework is a type of ORM (object relationship model) that connects classes
with database objects. It makes it easier to work with databases and tables
without worrying about columns and rows. ORM makes it easier for you to query
databases using LINQ, and you do not need to worry about your database
connection. Additionally, you can create programs that are unaware of the
database and its connection or type (Oracle, SQL Server or MySQL). Entity
framework takes care of all of the back-end connection so you can worry about
the queries and data.
Question
1: Design a code first data model which has a Project class that can contain a
bunch of tasks.
For our discussion, we will assume
that we are using the Code First model and that our model is made up of the
following 2 classes:
using
System;
using
System.Collections.Generic;
namespace
EFDemo.Model
{
//
Code first relies on a programming pattern
//
referred to as convention over configuration.
//
What this means is that if you want to use code first,
//
your classes need to follow the certain conventions
//
while defining the schema.
//
This allows EF to infer the schema that it needs to
//
create to get the job done.
public class Project
{
// Code First infers this as the primary key column
public int Id { get; set; }
// this becomes a nullable column
public string Name { get; set; }
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
}
public class Task
{
// Code First infers this as the primary key column
public int TaskId { get; set; }
public string Name { get; set; }
public DateTime StartDate {
get; set; }
public DateTime EndDate { get;
set; }
// this is inferred as Foreign key to project table
public int ProjectId { get; set; }
}
}
This model produces the following
database. I have highlighted the relevant items that I would like you to
understand before we proceed further.
Now let’s review a few simple
entity framework interview questions.
Question
2: Using Code First model, how can I mark a field/property as the primary key
if it does not follow the code first convention?
In our case above, EF looks for the
word “ID” with a combination with the entity name (e.g. Project) to determine
both the EntityKey and the primary key. If we rename the “Id” to say
“UniqueProjectIdentifier”, we will need to decorate that property with the
KeyAttribute ([Key]) to make it all work.
In the code below, we redefined our
primary key but did not provide any data annotations.
public
class
Project
{
//
Code First has to be told that
//
this as the primary key column
public int UniqueProjectIdentifier { get; set; }
//
this becomes a nullable column
public string Name { get; set; }
public string Description { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
}
This produces the following error:
The fix is simple. Just add the
[Key] attribute as shown below.
public
class
Project
{
//
Code First has to be told that
//
this as the primary key column
[Key]
public int UniqueProjectIdentifier { get; set; }
//
this becomes a nullable column
public string Name { get; set; }
public string Description { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
}
Question
3: When you have a annotate a property as Primary key in a table, how do you
enable foreign key relationship from another table?
Although this “fix” solved the
primary key issue for the Project class, it failed to infer our Foreign Key
relationship in the Task class. It actually created a new FK and ignored our
ProjectId key.
Now that we have a custom primary
key, we also have to annotate a foreign key for the Task table. The solution is
to define a navigation property for Task and annotate it to mark the ProjectId
property as the FK.
public
class
Task
{
//
Code First infers this as the primary key column
public int TaskId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
//
this is inferred as Foreign key to project table
public int ProjectId { get; set; }
//
explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
}
Question
4: How do you mark a property as required? For example, For a Project, the Name
is a required field.
You use the [Required] attribute to
mark a property as required.
public
class
Project
{
//
Code First has to be told that
//
this as the primary key column
[Key]
public int UniqueProjectIdentifier { get; set; }
//
this becomes a non-nullable column
[Required]
public string Name { get; set; }
public string Description { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
}
Question
5: How do you enforce a field to have a minimum and maximum number of
characters? For example, the Description on a Project should be a minimu of 10
and a maximum of 500?
EF provides us with convenient
property annotations of MinLength and maxLength.
public
class
Project
{
//
Code First has to be told that
//
this as the primary key column
[Key]
public int UniqueProjectIdentifier { get; set; }
//
this becomes a non-nullable column
[Required]
public string Name { get; set; }
[MaxLength(500, ErrorMessage="Maximum of 500 characters please")]
[MinLength(10, ErrorMessage="Minimum of 10 characters required")]
public string Description { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
}
After the 2 changes described
above, our database looks like:
Question
6: Define a property in project class named ProjectCode that is not mapped to
the database. ProjectCode is internally calculated as a combination of project
ID and Title.
Normally, in code first convention,
all properties are mapped to the database. If we want to exclude a specific
property (generally a computed property), we can annotate it with [NotMapped]
attribute.
public
class
Project
{
//
Code First has to be told that
//
this as the primary key column
[Key]
public int UniqueProjectIdentifier { get; set; }
//
this becomes a non-nullable column
[Required]
public string Name { get; set; }
[MaxLength(500, ErrorMessage="Maximum of 500 characters please")]
[MinLength(10, ErrorMessage="Minimum of 10 characters required")]
public string Description { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
[NotMapped]
public string ProjectCode
{
get
{
return UniqueProjectIdentifier
+ Name;
}
}
}
Question
7: If your domain entities are defined using a set of classes, how can you
combine them in EF to form one complete entity?
Let us assume that our Project
class has another class called ProjectDetails which has date created and the
description field. Using normal EF code first data model, EF will create 3
tables. But we want to tell EF to create only 2 tables (Project and task). To
achieve this we will use the [ComplexType] annotation on the Project Details as
shown below:
public class Project
{
//
Code First has to be told that
//
this as the primary key column
[Key]
public int UniqueProjectIdentifier { get; set; }
//
this becomes a non-nullable column
[Required]
public string Name { get; set; }
//
references the complex type as part of the
//
project object in the database
public ProjectDetails Details { get; set; }
//
list of tasks for a project
public virtual List<Task> Tasks { get; set; }
[NotMapped]
public string ProjectCode
{
get { return UniqueProjectIdentifier
+ Name;}
}
}
[ComplexType]
public
class
ProjectDetails
{
public DateTime? DateCreated { get; set; }
[MaxLength(500, ErrorMessage = "Maximum of 500 characters please")]
[MinLength(10, ErrorMessage = "Minimum of 10 characters required")]
public string Description { get; set; }
}
This results in the following
database schema:
The calling code also needs to be
changed:
class Program
{
static void Main(string[] args)
{
Database.SetInitializer<EFDemoContext>(new
DropCreateDatabaseIfModelChanges<EFDemoContext>());
using (var ctx = new EFDemoContext())
{
Project p = new Project()
{
Name = "Project 1",
Details = new ProjectDetails()
{
DateCreated =
DateTime.Now,
Description = "some project description"
}
};
ctx.Projects.Add(p);
ctx.SaveChanges();
}
}
}
Question
8: How can you tell EF to have a different table or column name than that
defined for the class?
By convention, EF defines the table
and column names based on your class and property names. You can use the
[Table] and [Column] annotations to tell EF to use different names.
[Table("ProjectItems")]
public
class
Task
{
//
Code First infers this as the primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
//
this is inferred as Foreign key to project table
public int ProjectId { get; set; }
//
explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
}
This causes EF to create a data
model where the Tasks table is represented by Projectitems and the StartDate
column to be named as CreationDate.
Question
9: For a datetime property, how can you tell EF to automatically compute and
insert the current date time when the row is created?
In our Project tasks, we want to
automatically set the creation date when a new row is inserted. We can achieve
this by telling EF that this property is a [DatabaseGenerated] property and
that it is computed.
[Table("ProjectItems")]
public
class
Task
{
//
Code First infers this as the primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
//
this is inferred as Foreign key to project table
public int ProjectId { get; set; }
//
explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
}
This code will throw an exception.
Why? Because code first won't be able to determine the formula for the computed
column. To solve this, you should only use this when pointing to existing
databases OR use the [TimeStamp] column.
Another use of this attribute is
when you do NOT want your primary key to be an auto incremented.
Question
10: When two tables have multiple relationships (for example, a task is created
by employee 1 and updated by employee 2), who do you indicate which
relationships go with which property?
Entity Framework provides us with
[InverseProperty] attribute to indicate multiple relationships between two
tables. Consider the following code first model where the Task class now has 2
pointers to Employee for CreatedBy and UpdatedBy. Also we have added an
Employee class which has a list of tasks created and updated. NOTE that we have
not (yet) added any data annotations to signify any inverse relationships. The
goal is to show you how EF will not be able to recognize this.
[Table("ProjectItems")]
public
class
Task
{
//
Code First infers this as the primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
//
this is inferred as Foreign key to project table
public int ProjectId { get; set; }
//
explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
public Employee CreatedBy { get; set; }
public Employee UpdatedBy { get; set; }
}
public
class
Employee
{
public int Id { get; set; }
public string name { get; set; }
public List<Task> TasksCreated { get; set; }
public List<Task> TasksUpdated { get; set; }
}
The database generated on running
this model is shown below:
As you can see above, the Tasks
(ProjectItems) table is not what you really expected. Let’s fix this by using
the [Inverseproprty] attribute.
public
class
Employee
{
public int Id { get; set; }
public string name { get; set; }
[InverseProperty("CreatedBy")]
public List<Task> TasksCreated { get; set; }
[InverseProperty("UpdatedBy")]
public List<Task> TasksUpdated { get; set; }
}
Now that we let EF now the
relationships, it is able to figure it out and generates the following database
for us:
What is the difference between Service endpoint and Client
endpoint?
Endpoint in WCF service is the
combination of three things address, binding and contract. Service endpoint is
for the server, server where your WCF service is hosted. Service endpoint
defines where the service is hosted, what are the bindings and the contract
i.e. methods and interfaces.
While client endpoint is for
the client. Client endpoint specifies which service to connect, where it's
located etc.
Code of WCF Server end point
looks something as shown below.
WCF Client end point code looks
something as shown below.This is generated when you add service reference using
add service reference.
1: What is ADO.NET Entity Framework Network?
Answer:
ADO.NET Entity
Framework is an Object/Relational Mapping (ORM) framework. It allows
programmers to work with relational data as domain-specific objects without
writing rigorous codes for data access. Using the Entity Framework, the
programmers can write queries using LINQ, then retrieve and manipulate data as
strongly typed objects.
2:
What do you understand by the term ‘Code First Experience’ in relation with the
Entity Framework Network?
Answer:
The Entity
Framework allowing creation of entity models using code and can map to an
existing database or generate a database from the model.
3:
What is the difference between the ADO.NET and ADO.NET Entity Framework
Network?
Answer:
ADO.NET is a set of
classes that provides data access services for .NET Framework programmers. The
goal of present version of ADO.NET is to eliminate the mismatch between the
data models and various languages faced by the programmers and thus to increase
the level of abstraction for data programming. To achieve this, the present
version of ADO.NET includes two techniques, namely the Language-Integrated
Query (LINQ) and the ADO.NET Entity Framework. Therefore, the Entity Framework
is a part of the ADO.NET family of technologies
that allows the object oriented mapping of relational data.
4:
Is it possible to carry forward the existing applications built on ADO.NET to the
Entity Framework?
Answer:
Yes, because it is
built on the existing ADO.NET provider model.
5:
Is it possible to change the mappings between the object model and the
database/XML (data storage) schema without changing the application code?
Answer:
Yes.
6:
What is the purpose of the Entity Data Model wizard?
Answer:
It creates an
entity data model from a database.
7:
What are the basic features of the entity data model?
Answer:
The basic features
of an entity data model are entities, associations and properties.
8:
What would be the extension of the EDM file?
Answer:
edmx
9:
Is it possible to create an entity model without a pre-existing database?
Answer:
Yes, it is possible
to create an entity model without a pre-existing database and then generating a
database from the model using the Entity Framework.
10:
True or False: With Entity Framework the queried data is returned as rows and
columns or data table records.
Answer:
False; Data is
retrieved as objects.
11: How are Changes in data saved?
Answer:
As data is returned
as objects, when these objects are saved, the changes are saved in the
database.
12:
How do entities differ from object?
Answer:
Entities define the
schema of an object but not the behavior of the object.
13:
What is the difference between the database model and entity data model?
Answer:
The entity data
model reflects the business domain, whereas the database model provides the
normalized schema designed by the database administrator.
14:
What are the two ways of writing queries with the Entity Framework syntax?
Answer:
LINQ to Queries and Entity
SQL
15:
How Entity Framework manages entities that do not inherit from the EntityObject?
Answer:
It manages these
objects as POCO (Plain Old CLR objects) entities.
16:
What is the purpose of Object Services?
Answer:
Object Services
keep track of any entity object instantiated either as a query result or by
creating a new object in code. Object services construct INSERT, UPDATE,
or DELETE command for each object added,
modified or deleted by comparing the original values with the current values.
Object services also pass the current values to any stored procedure, if
required.
17:
Does Entity Framework support foreign keys?
Answer:
Yes
18: What is the purpose of the EntityClient API in Entity
Framework?
Answer:
It provides the
functionalities required for connecting with the database, executing commands,
retrieving the query results and rearranging the results to match the entity
data model.
19:
Is it possible to use Entity Framework with web services and WCF?
Answer:
Yes
20:
True or False: Entity Framework moves the entity model into three XML files
that are used by the EF runtime.
Answer:
True
Net Entity Framework Interview questions and answers
|
Entity
Framework
|
|
-
|
What is .NET Entity Framework
?
|
|
|
The Microsoft ADO.NET Entity
Framework is an Object/Relational Mapping (ORM) framework that enables
developers to work with relational data as domain-specific objects,
eliminating the need for most of the data access plumbing code that
developers usually need to write.
|
|
-
|
What is EDM (Entity Data
Model)?
|
|
|
EDM consist three main parts-
i) Conceptual model ii) Mapping iii)Storage model.
|
|
-
|
What is Storage Model?
|
|
|
Storage model is the database
design model which consists of tables, views, stored procedures and their
relationships and keys.
|
|
-
|
What is minimum requirement
for Entity Framework applications to run?
|
|
|
Entity Framework applications
can run on any computer on which the .NET Framework starting with version 3.5
included.
|
|
-
|
What is MSL?
|
|
|
Mapping specification language
(MSL) is an XML-based language that describes the mapping between the
conceptual model and storage model of an Entity Framework application.
|
|
-
|
What is CSDL?
|
|
|
Conceptual schema definition
language (CSDL) is an XML-based language that describes the entities,
relationships, and functions that make up a conceptual model of a data-driven
application. This conceptual model can be used by the Entity Framework or WCF
Data Services.
|
|
-
|
What is SSDL?
|
|
|
Store schema definition
language (SSDL) is an XML-based language that describes the storage model of
an Entity Framework application.
|
|
-
|
What is Mapping in Entity
Framework?
|
|
|
Mapping contains the
information about conceptual model which is mapped to storage model.
|
|
-
|
What is EntitySet?
|
|
|
EntitySet is a container for
EntityType. It is set of same entitytype. It is like db table.
|
|
-
|
What is EntityType?
|
|
|
EntityType is a datatype in the
model.
Each EntityType for conceptual model in described in XML.
|
|
-
|
Describe Entity Lifecycle?
|
|
|
i) Added
ii)Deleted
iii) Modified
iv) Unchanged
v) Detached
|
|
-
|
What is Entity Graph?
|
|
|
One Entity has relation with
other entities is known as entity graph.
Likewise Employee entity graph includes many other entities like
Employee Address, Employee code etc.
|
|
-
|
What is the advantages of
Entity Framework:
|
|
|
i) Database performance is
improved. Database operations like select, insert, update, delete will work
faster as we have not to execute in qry browser again and again.
ii) Entity Framework performing basic CRUD (Create, Read, Update,
Delete) operations. So most of the time you don't have to write any SQL
yourself. When you make any changes to the object, the ORM will usually
detect this, and mark the object as 'modified'.
iii)Entity Framework works on databases other than Microsoft SQL
Server, like Oracle, MySQL etc. While Linq is limited to MS SQL Server.
iv)Ability to have inheritance relationships between entities.
|
|
-
|
What is a .edmx file?
|
|
|
What is a .edmx file? Visual
Studio saves the entire Entity Data Model configurations in a file with an
.edmx extension. This file has an XML format. The .edmx file mainly has three
sections namely the storage schema, conceptual schema and the mappings.
|
|
-
|
Does Entity Framework support
CRUD operations?
|
|
|
Yes.
CRUD included (Create, Read, Update, Delete), these are supported by
Entity Framework.
|
|
-
|
What is POCO in EF?
|
|
|
POCO Stands for Plain Old CLR
Object. POCOs contain only data and domain logic. It has data, validation,
and any other business logic that you want to put. It provides separation of
business logic and persistence logic, which is more in line with the Single
Responsibility Principle.
|
|
-
|
What is Code First Approach?
|
|
|
Entity Framework supported the
development of applications using Schema first and Model First approach.
In Code First approach, we are creating the code first and the Entity
framework will generate the corresponding Database according to code.
|
|
-
|
What is Model First Approach?
|
|
|
Entity Framework allows us to
model the entities. In Visual Studio, it is required to write code against
the model and then test the complete application without having a physical
database. If everything goes well, we can generate the schema for the
database from the model.
|
|
-
|
Does Entity Framework support
LINQ ?
|
|
|
Yes.
The Entity Framework includes LINQ to Entities which exposes many of
the same features as LINQ to SQL over your conceptual application data model.
|
|
-
|
What is Enterprise Scenarios
?
|
|
|
The Entity Framework has
features targeting "Enterprise Scenarios". In an enterprise, the
database is typically controlled by a DBA, the schema is generally optimized
for storage considerations (performance, consistency, partitioning) rather
than exposing a good application model, and may change over time as usage
data and usage patterns evolve
|
Question
1: Design a code first data model which has a Project class that can contain a
bunch of tasks.
For our
discussion, we will assume that we are using the Code First model and that our
model is made up of the following 2 classes:
using System;
using System.Collections.Generic;
namespace EFDemo.Model
{
// Code first relies on a programming
pattern
// referred to as convention over
configuration.
// What this means is that if you
want to use code first,
// your classes need to follow the
certain conventions
// while defining the schema.
// This allows EF to infer the schema
that it needs to
// create to get the job done.
public class Project
{
// Code First infers this as the
primary key column
public int Id { get; set; }
// this becomes a nullable column
public string Name { get; set; }
public string Description { get;
set; }
// list of tasks for a project
public virtual List<Task>
Tasks { get; set; }
}
public class Task
{
// Code First infers this as the
primary key column
public int TaskId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get;
set; }
public DateTime EndDate { get;
set; }
// this is inferred as Foreign
key to project table
public int ProjectId { get; set;
}
}
}
This model
produces the following database. I have highlighted the relevant items that I
would like you to understand before we proceed further.
Now let’s
review a few simple entity framework interview questions.
Question
2: Using Code First model, how can I mark a field/property as the primary key
if it does not follow the code first convention?
In our case
above, EF looks for the word “ID” with a combination with the entity name (e.g.
Project) to determine both the EntityKey and the primary key. If we rename the
“Id” to say “UniqueProjectIdentifier”, we will need to decorate that property
with the KeyAttribute ([Key]) to make it all work.
In the code
below, we redefined our primary key but did not provide any data annotations.
public class Project
{
// Code First has to be told that
// this as the primary key column
public int UniqueProjectIdentifier {
get; set; }
// this becomes a nullable column
public string Name { get; set; }
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
}
This
produces the following error:
The fix is
simple. Just add the [Key] attribute as shown below.
public class Project
{
// Code First has to be told that
// this as the primary key column
[Key]
public int UniqueProjectIdentifier {
get; set; }
// this becomes a nullable column
public string Name { get; set; }
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
}
Question
3: When you have a annotate a property as Primary key in a table, how do you
enable foreign key relationship from another table?
Although
this “fix” solved the primary key issue for the Project class, it failed to
infer our Foreign Key relationship in the Task class. It actually created a new
FK and ignored our ProjectId key.
Now that we
have a custom primary key, we also have to annotate a foreign key for the Task
table. The solution is to define a navigation property for Task and annotate it
to mark the ProjectId property as the FK.
public class Task
{
// Code First infers this as the
primary key column
public int TaskId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set;
}
public DateTime EndDate { get; set; }
// this is inferred as Foreign key to
project table
public int ProjectId { get; set; }
// explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get;
set; }
}
Question
4: How do you mark a property as required? For example, For a Project, the Name
is a required field.
You use the
[Required] attribute to mark a property as required.
public class Project
{
// Code First has to be told that
// this as the primary key column
[Key]
public int UniqueProjectIdentifier {
get; set; }
// this becomes a non-nullable column
[Required]
public string Name { get; set; }
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
}
Question
5: How do you enforce a field to have a minimum and maximum number of
characters? For example, the Description on a Project should be a minimu of 10
and a maximum of 500?
EF provides
us with convenient property annotations of MinLength and maxLength.
public class Project
{
// Code First has to be told that
// this as the primary key column
[Key]
public int UniqueProjectIdentifier {
get; set; }
// this becomes a non-nullable column
[Required]
public string Name { get; set; }
[MaxLength(500, ErrorMessage="Maximum
of 500 characters please")]
[MinLength(10, ErrorMessage="Minimum
of 10 characters required")]
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
}
After the 2 changes
described above, our database looks like:
Question
6: Define a property in project class named ProjectCode that is not mapped to
the database. ProjectCode is internally calculated as a combination of project
ID and Title.
Normally, in
code first convention, all properties are mapped to the database. If we want to
exclude a specific property (generally a computed property), we can annotate it
with [NotMapped] attribute.
public class Project
{
// Code First has to be told that
// this as the primary key column
[Key]
public int UniqueProjectIdentifier {
get; set; }
// this becomes a non-nullable column
[Required]
public string Name { get; set; }
[MaxLength(500, ErrorMessage="Maximum
of 500 characters please")]
[MinLength(10, ErrorMessage="Minimum
of 10 characters required")]
public string Description { get; set;
}
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
[NotMapped]
public string ProjectCode
{
get
{
return
UniqueProjectIdentifier + Name;
}
}
}
Question
7: If your domain entities are defined using a set of classes, how can you
combine them in EF to form one complete entity?
Let us
assume that our Project class has another class called ProjectDetails which has
date created and the description field. Using normal EF code first data model,
EF will create 3 tables. But we want to tell EF to create only 2 tables
(Project and task). To achieve this we will use the [ComplexType] annotation on
the Project Details as shown below:
public class
Project
{
// Code First has to be told that
// this as the primary key column
[Key]
public int UniqueProjectIdentifier {
get; set; }
// this becomes a non-nullable column
[Required]
public string Name { get; set; }
// references the complex type as
part of the
// project object in the database
public ProjectDetails Details { get;
set; }
// list of tasks for a project
public virtual List<Task> Tasks
{ get; set; }
[NotMapped]
public string ProjectCode
{
get { return
UniqueProjectIdentifier + Name;}
}
}
[ComplexType]
public class ProjectDetails
{
public DateTime? DateCreated { get;
set; }
[MaxLength(500, ErrorMessage = "Maximum
of 500 characters please")]
[MinLength(10, ErrorMessage = "Minimum
of 10 characters required")]
public string Description { get; set;
}
}
This results
in the following database schema:
The calling
code also needs to be changed:
class
Program
{
static void Main(string[] args)
{
Database.SetInitializer<EFDemoContext>(new
DropCreateDatabaseIfModelChanges<EFDemoContext>());
using (var ctx = new EFDemoContext())
{
Project p = new Project()
{
Name = "Project
1",
Details = new
ProjectDetails()
{
DateCreated =
DateTime.Now,
Description = "some
project description"
}
};
ctx.Projects.Add(p);
ctx.SaveChanges();
}
}
}
Question
8: How can you tell EF to have a different table or column name than that
defined for the class?
By
convention, EF defines the table and column names based on your class and
property names. You can use the [Table] and [Column] annotations to tell EF to
use different names.
[Table("ProjectItems")]
public class Task
{
// Code First infers this as the
primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
public DateTime StartDate { get; set;
}
public DateTime EndDate { get; set; }
// this is inferred as Foreign key to
project table
public int ProjectId { get; set; }
// explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get;
set; }
}
This causes
EF to create a data model where the Tasks table is represented by Projectitems
and the StartDate column to be named as CreationDate.
Question
9: For a datetime property, how can you tell EF to automatically compute and
insert the current date time when the row is created?
In our
Project tasks, we want to automatically set the creation date when a new row is
inserted. We can achieve this by telling EF that this property is a
[DatabaseGenerated] property and that it is computed.
[Table("ProjectItems")]
public class Task
{
// Code First infers this as the
primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime StartDate { get; set;
}
public DateTime EndDate { get; set; }
// this is inferred as Foreign key to
project table
public int ProjectId { get; set; }
// explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get;
set; }
}
This code
will throw an exception. Why? Because code first won't be able to determine the
formula for the computed column. To solve this, you should only use this when
pointing to existing databases OR use the [TimeStamp] column.
Another use
of this attribute is when you do NOT want your primary key to be an auto
incremented.
Question
10: When two tables have multiple relationships (for example, a task is created
by employee 1 and updated by employee 2), who do you indicate which
relationships go with which property?
Entity
Framework provides us with [InverseProperty] attribute to indicate multiple
relationships between two tables. Consider the following code first model where
the Task class now has 2 pointers to Employee for CreatedBy and UpdatedBy. Also
we have added an Employee class which has a list of tasks created and updated.
NOTE that we have not (yet) added any data annotations to signify any inverse
relationships. The goal is to show you how EF will not be able to recognize
this.
[Table("ProjectItems")]
public class Task
{
// Code First infers this as the
primary key column
public int TaskId { get; set; }
public string Name { get; set; }
[Column("CreationDate")]
public DateTime StartDate { get; set;
}
public DateTime EndDate { get; set; }
// this is inferred as Foreign key to
project table
public int ProjectId { get; set; }
// explicitly define the FK
[ForeignKey("ProjectId")]
public virtual Project Project { get;
set; }
public Employee CreatedBy { get; set;
}
public Employee UpdatedBy { get; set;
}
}
public class Employee
{
public int Id { get; set; }
public string name { get; set; }
public List<Task> TasksCreated
{ get; set; }
public List<Task> TasksUpdated
{ get; set; }
}
The database
generated on running this model is shown below:
As you can
see above, the Tasks (ProjectItems) table is not what you really expected.
Let’s fix this by using the [Inverseproprty] attribute.
public class Employee
{
public int Id { get; set; }
public string name { get; set; }
[InverseProperty("CreatedBy")]
public List<Task> TasksCreated
{ get; set; }
[InverseProperty("UpdatedBy")]
public List<Task> TasksUpdated
{ get; set; }
}
Now that we
let EF now the relationships, it is able to figure it out and generates the
following database for us:
I hope that
post has been helpful to you to understand a few of the data annotations
provided by Entity framework.
1) Explain what is
LINQ? Why is it required?
Language Integrated Query or LINQ is the
collection of standard query operators which provides query facilities into.NET
framework language like C#, VB.NET.
LINQ is required as it bridges the gap between
the world of data and world of objects.
2) What are the types
of LINQ?
·
LINQ to Objects
·
LINQ to XML
·
LINQ to Dataset
·
LINQ to SQL
·
LINQ to Entities
3) Explain how LINQ
is useful than Stored Procedures?
·
Debugging: It is difficult to debug a stored procedure but as LINQ is part
of.NET, visual studios debugger can be used to debug the queries
·
Deployment: For stored procedure, additional script should be provided but
with LINQ everything gets compiled into single DLL hence deployment becomes
easy
·
Type Safety: LINQ is type safe, so queries errors are type checked at compile
time
4) List out the three
main components of LINQ? Explain what is the extension of the file, when LINQ
to SQL is used?
Three main components of LINQ are
·
Standard Query Operators
·
Language Extensions
·
LINQ Providers
The extension of the file used is .dbml
5) Define what is
Where clause and Let clause?
·
Where clause: It allows adding
some conditional filters to the query.
·
Let clause: It allows
defining a variable and assigning it a value calculated from the data values.
6) Explain why SELECT
clause comes after FROM clause in LINQ?
With other programming language and C#, LINQ
is used, it requires all the variables to be declared first. “FROM” clause of
LINQ query defines the range or conditions to select records. So, FROM clause
must appear before SELECT in LINQ.
7) Explain what is
the use of System.XML.Xlinq.dll?
System.Data.Dlinq.dll provides the
functionality to work with LINQ to SQL
8) Explain what is
lambda expressions in LINQ?
Lambda expression is referred as a unique
function use to form delegates or expression tree types, where right side is
the output and left side is the input to the method. For writing LINQ queries
particularly, Lambda expression is used.
9) Explain how LINQ
with databases can be used?
LINQ supports XML, SQL, Dataset and Objects. Through LINQ to
objects or LINQ to Datasets one can use LINQ with other databases. The objects
and datasets take care of database particular operations, and LINQ only needs to deal with those
objects and not the database operations directly.
10) Explain what is
the difference between Skip() and SkipWhile() extension method?
·
Skip() : It will take an
integer argument and from the given IEnumerable it skips the top n numbers
·
SkipWhile (): It will continue to skip the elements as far as the input
condition is true. It will return all remaining elements if the condition is
false
11) In LINQ how will
you find the index of the element using where () with Lambda Expressions?
In order to find the index of the element
using where () with the lambda expression
Where ( ( i, ix ) => i == ix);
12) Explain how you
can assign a lambda expression to a delegate?
To assign a lambda expression to a delegate
Delegate int del (int i);
Del myDelegate=x=>x*x;
Intj = myDelegate (4); //j=16
13) Explain what is
the difference between Statement Lambda and Expression Lambda?
·
Expression Lambdas are extensively used in the construction of
Expression Trees
·
To create expression trees statement lambdas cannot be used
14) Mention what is
the role of DataContext classes in LINQ?
DataContext class acts as a bridge between SQL
Server database and the LINQ to SQL. For accessing the database and also for
changing the data in the database, it contains connections string and the
functions.
15) Explain what are
LINQ query expressions?
Query expression is nothing but an LINQ query.
It is a combination of query clauses that identifies the data sources for a
query. It contains information for sorting, filtering, grouping or joining to
apply to the source data. It determines what information should be retrieved
from the data source.CV.
16) Explain what are
compiled queries?
In compiled LINQ queries, the plan is cached
in a static class and static class is a global cache. Rather than preparing the
query plan from scratch, LINQ prepares plan using stating class object.
17) Explain how
standard query operators useful in LINQ?
Standard Query Operators useful in LINQ are
·
Get a total count of elements in the collection
·
Order the results of a collection
·
Grouping
·
Computing average
·
Joining two collections based on matching keys
·
Filter the results
18) Explain what is
the purpose of LINQ providers in LINQ?
LINQ providers are set of classes that take an
LINQ query which generates method that executes an equivalent query against a
particular data source.
19) Explain how you
can retrieve a single row with LINQ?
To retrieve a single row with LINQ we need
Public User GetUser
(string userName)
{
DBNameDataContext
myDB = new DBNameDataContext ( ) ;
User user = myDB.
Users. Single ( u, u.UserName => userName );
Return user;
}
20) LINQ query is
executed in which statement?
In VB, an LINQ query is executed in the For
Each Statement, and in the foreach statement for C#.
21) Explain what is
“LINQ to Objects”?
When LINQ queries any IEnumerable(Of T)
collection or IEnumerable directly without the use of an intermediate LINQ
provider or API such as LINQ to SQL or LINQ to XML is referred as “LINQ to
Objects.”
22) Explain how you
can differentiate between Conversion Operator “ToDictionary” and “IEnumerable”
of LINQ?
To solve the conversion type problems
“IEnumerable” and “ToDictionary” conversion operator are used.
“ToDictionary” conversion operator is the
instance of Dictionary (k, T). The “keySelector” predicate recognizes the key
of each item, while “elementSelector”, is used to extract each single item, if
it is given.
Extension method on “IEnumerable”
is.AsEnumerable. AsEnumerable simply returns the source sequence as an object
of type IEnumerable <T>