Entity Framework
ADO.NET Entity Framework Interview Questions
IMP ADO.NET Entity Framework Interview Questions
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.
High-level capabilities of the Entity Framework:
Works with a variety of database servers (including Microsoft SQL Server, Oracle, and DB2)
Includes a rich mapping engine that can handle real-world database schemas and works well with stored procedures
Provides integrated Visual Studio tools to visually create entity models and to auto-generate models from an existing database. New databases can be deployed from a model, which can also be hand-edited for full control
Provides a Code First experience to create entity models using code. Code First can map to an existing database or generate a database from the model.
Integrates well into all the .NET application programming models including ASP.NET, Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), and WCF Data Services (formerly ADO.NET Data Services)
The Entity Framework is built on the existing ADO.NET provider model, with existing providers being updated additively to support the new Entity Framework functionality. Because of this, existing applications built on ADO.NET can be carried forward to the Entity Framework easily with a programming model that is familiar to ADO.NET developers.
Using the Entity Framework to write data-oriented applications provides the following benefits:
Reduced development time: the framework provides the core data access capabilities so developers can concentrate on application logic.
Developers can work in terms of a more application-centric object model, including types with inheritance, complex members, and relationships. In .NET Framework 4, the Entity Framework also supports Persistence Ignorance through Plain Old CLR Objects (POCO) entities.
Applications are freed from hard-coded dependencies on a particular data engine or storage schema by supporting a conceptual model that is independent of the physical/storage model.
Mappings between the object model and the storage-specific schema can change without changing the application code.
Language-Integrated Query support (called LINQ to Entities) provides IntelliSense and compile-time syntax validation for writing queries against a conceptual model.
The Entity Framework uses the Entity Data Model (EDM) to describe the application-specific object or “conceptual” model against which the developer programs. The EDM builds on the widely known Entity Relationship model (introduced by Dr. Peter Chen) to raise the abstraction level above logical database schemas. The EDM was developed with the primary goal of becoming the common data model across a suite of developer and server technologies from Microsoft. Thus an EDM created for use with the Entity Framework can also be leveraged with WCF Data Services (formerly ADO.NET Data Services), Windows Azure Table Storage, SharePoint 2010, SQL Server Reporting Services, and SQL Server PowerPivot for Excel, with more coming in the future.
EF – Enterprise Development, L2S – Rapid Application Development.
EF – Works with all data sources, L2S – Mainly works with SQL Server.
EF – Works with Conceptual model of database, L2S – Works with objects in database.
EF – “.EDMX” is created, L2S – “.dbml” is created.
L2S does not support POCO mapping, EF does.
EF has more flexibility (code first, model first, database first). L2SQL has only 1.
EF has support for SPROC -> POCO mapping.
EF has Entity-SQL, allowing you to go back to classic ADO.NET when required. You can build queries in LINQ (or in “Entity SQL”, a canonical version of SQL extended to support concepts like strong typing, polymorphism, relationship navigation and complex types), return results as strongly typed CLR objects, execute stored procedures or table valued functions through strongly-typed methods, and process changes by calling a single save method.
EF allows mapping a single class to multiple tables.
EF supports inheritance (TPT, TPH)
EF will handle M-M relationships
EF goes hand-in-hand with Repository pattern, and deferred execution via IQueryable
L2S is still slightly better than L2E at translating LINQ queries that use normal CLR methods into TSQL. L2E supports more or less the same things but through its’ own EntityFunctions class: http://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions.aspx.
http://career.guru99.com/top16-ado-net-entity-framework-interview-questions/
Performance
L2S runtime is more lightweight than EF (due to only a single layer; EF has to deal with two model layers and the mappings between them).
EF often generates a bit more verbose TSQL than L2S but most of the time that only affects readability if you’re profiling and looking at the generated queries; the SQL optimizer will end up with the same execution plan most of the time. There are however some cases when the queries can grow so large and complex that it can have a performance impact.
L2S is also slightly better at doing client-side optimization of queries; it eliminates where clause predicates that can be evaluated client-side so the database don’t have to worry about them. This means less work for SQL Server’s optimizer, and less risk that you’ll end up with a ‘bad’ execution plan.
Model First:
Good support with EDMX designer
We can visually create the database model
EF generates the Code and database script
Extensible through partial classes
We can modify the model and update the generated database.
Database First:
An existing database can be used
Code can be auto-generated.
Extensible using partial classes/ T4 templates
The developer can update the database manually
There is a very good designer, which sync with the underlining database
Code First:
There is full control of the model from the Code; no EDMX/designer
No manual intervention to DB is required
The database is used for data only
Hardcode coders love to code the model using the Code First approach. In this approach, the database is used for storing the data only. The database structure is defined by various classes. One of the advantages of the Code First approach is the same class is used for defining the database table structure and business object. Any changes in the class affect both the business object and the database table.
---------------------------------------------------------------------------------------------------------------------------------------------------------
XDocument xDoc = XDocument.Load(fileName);
XElement xe = new XElement("Item",
new XElement("Name", lib.Name),
new XElement("Fullpath", lib.Fullpath),
new XElement("SystemFullpath", lib.SystemFullpath),
new XElement("Created", lib.Created));
xDoc.Element("Library").Add(xe);
xDoc.Save(fileName);
------------------------------------------------------------------------------
List<Library> libList = new List<Library>();
if (File.Exists(fileName))
{
XDocument xDoc = XDocument.Load(fileName);
var items = from item in xDoc.Descendants("Item")
select new
{
Name = item.Element("Name").Value,
FullPath = item.Element("FullPath").Value,
Created = item.Element("Created").Value
};
if (items != null)
{
foreach (var item in items)
{
Library lib = new Library();
lib.Name = item.Name;
lib.Fullpath = item.FullPath;
lib.Created = DateTime.Parse(item.Created);
libList.Add(lib);
}
}
}
--------------------------------------------------------------------------------------------------------------------
public void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
//To add theme in pre_init
Page.Theme = ConfigurationManager.AppSettings["ESPL_Theme"].ToString();
static void CountWordOccurrence()
{
//tell the user to enter their sentence
Console.WriteLine("\nPlease enter the sentence to be tested.");
//split their input into a string array
string[] words = Console.ReadLine().Split(' ');
//create our SortedList for holding our words and their count
SortedList wordList = new SortedList();
//variable to hold how many times a word appears in the string
int numWords = 0;
//now we loop through the string array
foreach (string word in words)
{
//check and see if this word is in our list yet
if (!(wordList.ContainsKey(word)))
{
//it isnt there so we add it with a value of 1
//since it's the words first occurrence
wordList.Add(word, 1);
//increment our word counter
numWords++;
}
else
{
//since the word dous exist we get the count of times it exists
int iWordCount = (int)wordList[word];
//we then increment the count for that word in the list
wordList[word] = iWordCount + 1;
}
}
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
Lazy loading
Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading objects unnecessarily.
http://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading
Rules for lazy loading:
context.Configuration.ProxyCreationEnabled should be true.
context.Configuration.LazyLoadingEnabled should be true.
Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual.
https://msdn.microsoft.com/en-in/data/jj574232.aspx
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.
var query = context.Categories.Take(3); // Lazy loading
Eager loading
In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.
var query = context.Categories.Include("Products").Take(3); // Eager loading
Explicitly loading
Even with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call. To do so you use the Load method on the related entity’s entry. For example:
using (var context = new BloggingContext())
{ var post = context.Posts.Find(2);
// Load the blog related to a given post
context.Entry(post).Reference(p => p.Blog).Load();
Starting with EF6 the framework now provides:
Database.BeginTransaction() : An easier method for a user to start and complete transactions themselves within an existing DbContext – allowing several operations to be combined within the same transaction and hence either all committed or all rolled back as one. It also allows the user to more easily specify the isolation level for the transaction.
Database.UseTransaction() : which allows the DbContext to use a transaction which was started outside of the Entity Framework.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using (EFModelFirst_DemoContainer context = new EFModelFirst_DemoContainer())
{
using (var transaction = context.Database.BeginTransaction())
try
{
Category c = new Category();
c.CategoryName = "Mobile";
context.Categories.Add(c);
context.SaveChanges();
Product p = new Product();
p.CategoryId = c.CategoryId;
p.ProductName = "HTC";
p.Price = "15000";
context.Products.Add(p);
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
using(SqlConnection con = new SqlConnection("connectionString"))
{
con.Open();
using(var transaction = con.BeginTransaction())
{
// Do something....
//Pass this transaction to EF....
using (EntitiesContext context = new EntitiesContext(con, false))
{
context.Database.UseTransaction(transaction);
EmployeeMaster employee = new EmployeeMaster();
employee.Code = "A0001";
employee.Name = "Jignesh Trivedi";
employee.DepartmentId = 1;
context.Employees.Add(employee);
context.SaveChanges();
}
}
}
using (var context = new BloggingContext())
{ using (var dbContextTransaction = context.Database.BeginTransaction()) { try { context.Database.ExecuteSqlCommand( @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'" ); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); } } }
using (var conn = new SqlConnection("...")) { conn.Open(); using (var sqlTxn = conn.BeginTransaction(System.Data.IsolationLevel.Snapshot)) { try { var sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.Transaction = sqlTxn; sqlCommand.CommandText = @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'"; sqlCommand.ExecuteNonQuery(); using (var context = new BloggingContext(conn, contextOwnsConnection: false)) { context.Database.UseTransaction(sqlTxn); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); } sqlTxn.Commit(); } catch (Exception) { sqlTxn.Rollback(); } } }
LINQ
static void Main()
{
liqu ll = new liqu();
ll.liq12();
Console.ReadKey();
}
public void liq1()
{
/*int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var no = from n in num
where n > 5
select n;
foreach (var numeric in no)
{
Console.WriteLine(numeric);
}*/
int[] num = { 0, 1, 2, 3, 4, 5 };
string[] numString = { "Zero", "One", "Two", "Three", "Four", "Five" };
var no = from n in num
where n < 3
select numString[n];
foreach (var numeric in no)
{
Console.WriteLine(numeric);
}
/*List<Employee> emp = new List<Employee>();
Employee e = new Employee();
e.Name = "Ram";
e.Age = 25;
emp.Add(e);
Employee e1 = new Employee();
e1.Name = "Jhon";
e1.Age = 29;
emp.Add(e1);
Employee e2 = new Employee();
e2.Name = "Sunil";
e2.Age = 19;
emp.Add(e2);*/
/*var objEmp = from em in emp
where em.Age > 20
select em;
foreach (var emp1 in objEmp)
{
Console.WriteLine(emp1.Name + "--" + emp1.Age);
}*/
/* var objEmp = from em in emp
where em.Age > 20
select em.Name.ToUpper();
foreach (var emp1 in objEmp)
{
Console.WriteLine(emp1);
}*/
}
public void liq2()
{
List<Employee> emp = new List<Employee>();
Employee e = new Employee();
e.Name = "Ram";
e.Age = 25;
emp.Add(e);
Employee e1 = new Employee();
e1.Name = "Jhon";
e1.Age = 29;
emp.Add(e1);
Employee e2 = new Employee();
e2.Name = "Sunil";
e2.Age = 19;
emp.Add(e2);
var objEmp = from em in emp
where em.Age > 20
orderby em.Name, em.Age descending
select new { UserName=em.Name,UserAge=em.Age };
foreach (var emp1 in objEmp)
{
Console.WriteLine(emp1.UserName + "--" + emp1.UserAge);
}
}
public void liq4()
{
int[] numeric = { 1, 2, 3, 4, 5, 6, 7, 8 };
var no =from num in numeric
orderby num descending
select num;
var noo = no.Take(5);
var no1 = (noo.TakeWhile(n1 => n1 >6)).Take(1); //lamda expression....
foreach (var n in no1)
Console.WriteLine(n);
}
public void liq5()
{
int[] numeric = { 1, 2, 10, 4, 5, 6, 7, 8 };
var noo = from num in numeric
select num;
//var no1 = noo.Skip(5);
//Checking condition wont be applied once it fails while iterating the array.
var no1 = noo.SkipWhile(n1 => n1 < 6); //lamda expression....
foreach (var n in no1)
Console.WriteLine(n);
}
public void liq6()
{
int[] odd = { 1,3,5,7,9 };
int[] even = { 2,4,6,8,10 };
var noo = from od in odd
from evn in even
select new { od, evn };
//var no1 = noo.SkipWhile(n1 => n1 < 6); //lamda expression....
foreach (var n in noo)
Console.WriteLine(n.od +"--"+n.evn);
}
public void liq7()
{
int[] odd = { 1, 3, 5, 7, 9 };
int[] even = { 2, 4, 6, 8, 10 };
var noo = from od in odd
from evn in even
select new { od, evn };
var no1 = noo.Take(3);
//var no1 = noo.SkipWhile(n1 => n1 < 6); //lamda expression....
foreach (var n in no1)
Console.WriteLine(n.od + "--" + n.evn);
}
public void liq8()//Union
{
int[] odd = { 1, 3, 5, 7, 9 };
int[] even = { 2, 4, 6, 8, 10 };
/*var noo = from od in odd
from evn in even
select new { od, evn };*/
var no1 = odd.Union(even);
foreach (var n in no1)
Console.WriteLine(n);
}
public void liq9()//Intersect
{
int[] odd = { 1, 3, 5, 7, 9 };
int[] even = { 2, 3, 6, 8, 10 };
var no1 = odd.Intersect(even);
foreach (var n in no1)
Console.WriteLine(n);
}
public void liq10()//Sum
{
int[] odd = { 1, 3, 5, 7, 9 };
int[] even = { 2, 3, 6, 8, 10 };
var no1 = odd.Union(even);
var noo = no1.Sum();
Console.WriteLine(no1.Count());
Console.WriteLine(noo);
/*foreach (var n in noo)
Console.WriteLine(n);*/
}
public void liq11()//Sum
{
ArrayList str =new ArrayList();
str.Add(12.5);
str.Add("Ram");
str.Add(12);
str.Add("Sunil");
str.Add(18.50);
str.Add(null);
var noo = str.OfType<String>();
foreach (var n in noo)
Console.WriteLine(n);
}
//XML
class xpth
{
static void Main()
{
xpth objX = new xpth();
objX.xmlWrt2();
Console.ReadKey();
}
private void xmlRd()
{
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\stu.xml");
//doc.LoadXml("<Student><Name>Sunil</Name><Name>Jhon</Name></Student>");
//XmlNodeList objNodList = doc.SelectNodes("/Student/Name[@Age<=25]");
XmlNodeList objNodList = doc.SelectNodes("/Student/Name[position()<=1]");
foreach (XmlNode nod in objNodList)
{
Console.WriteLine(nod["FirstName"].InnerText + "--" + nod["LastName"].InnerText + "--" + nod.Attributes["Age"].InnerText);
}
}
private void xmlWrt()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Student><Name>Sunil</Name><Name>Jhon</Name></Student>");
doc.Save(@"D:\testxml1.xml");
}
private void xmlWrt2()
{
XmlTextWriter wrt = new XmlTextWriter(@"D:\testxml2.xml", null);
//wrt.Settings.Indent = true;
wrt.Formatting = Formatting.Indented;
wrt.WriteStartDocument();
wrt.WriteStartElement("Students");
wrt.WriteStartElement("Name");
wrt.WriteStartAttribute("Age");
wrt.WriteString("25");
wrt.WriteEndAttribute();
wrt.WriteStartElement("FirstName");
wrt.WriteString("Ram");
wrt.WriteEndElement();
wrt.WriteStartElement("LastName");
wrt.WriteString("Kumar");
wrt.WriteEndElement();
wrt.WriteEndElement();
wrt.WriteStartElement("Name");
wrt.WriteStartElement("FirstName");
wrt.WriteString("Jhon");
wrt.WriteEndElement();
wrt.WriteStartElement("LastName");
wrt.WriteString("David");
wrt.WriteEndElement();
wrt.WriteEndElement();
wrt.WriteEndElement();
wrt.WriteEndDocument();
wrt.Close();
}
}
//Collections
class collec
{
static void Main()
{
collec c = new collec();
c.fnStack();
c.fnQueue();
// c.fnAryList();
Console.ReadKey();
}
private void fnStack()
{
Stack objStk = new Stack();
objStk.Push("Jhon");
objStk.Push("Ram");
objStk.Push("Cegon");
objStk.Push("Sunil");
int n = objStk.Count;
n = n - 1;
for (int i = 0; i <= n; i++)
{
Console.WriteLine(objStk.Pop() + "---" + i.ToString());
}
}
private void fnQueue()
{
Queue objQue = new Queue();
objQue.Enqueue("Jhon");
objQue.Enqueue("Ram");
objQue.Enqueue("Cegon");
objQue.Enqueue("Sunil");
int n = objQue.Count;
n = n - 1;
for (int i = 0; i <= n; i++)
{
Console.WriteLine(objQue.Dequeue() + "---" + i.ToString());
}
}
private void fnAryList()
{
ArrayList objAry = new ArrayList();
objAry.Add("A");
objAry.Add("Bajana");
objAry.Add("C");
objAry.Add("D");
objAry.Insert(2, "T");
//objAry.RemoveAt(3);
//objAry.Sort();
//objAry.Reverse(1, 2);
if (objAry.Contains("D"))
{
Console.WriteLine("Exist");
}
int n = objAry.Count;
n = n - 1;
for (int i = 0; i <= n; i++)
{
Console.WriteLine(objAry[i].ToString() + "---" + i.ToString());
}
objAry.Clear();
}
}
//Delegates
#region "Class Delg"
class delg
{
#region "Global variable declaration"
delegate void delSample();
delegate void delSamplePar(int i);
#endregion
#region "Main function"
static void Main()
{
delg d = new delg();
delSample del = new delSample(d.fnName);
del += new delSample(d.fnAge);
del += new delSample(d.fnCity);
del -= new delSample(d.fnAge); //Multicast delegate...
//Ananomous Method...
//del += delegate()
//{
// Console.WriteLine("Ananomous Method");
//};
del();
//delSamplePar delp = new delSamplePar(d.fnAge);
//delp(55);
Console.ReadKey();
}
#endregion
private void fnName()
{
Console.WriteLine("Delegate function");
}
private void fnAge()
{
Console.WriteLine(25);
}
private void fnAge(int iAge)
{
Console.WriteLine(iAge);
}
private void fnCity()
{
Console.WriteLine("Blore");
}
}
#endregion
/////////////////////////////////////////////////////////////////////////////////////////////
<body onload="cls()">
function cls()
{
var txt= document.getElementById('<%=lblDate.ClientID %>');
txt.innerText=window.Date();
}
fnMsg();
function fnMsg()
{
//alert(window.Date());
//setTimeout("cls()",1000);
setInterval("cls()",1000);
}
---------------------------------------------------------------------------------------------------------------------------------
What is Type Safety?
Type safe means preventing programs from accessing memory outside the bounds of an object's public properties A programming language is type safe when the language defines the behavior for when the programmer treats a value as a type to which it does not belong. Type safety requires that well-typed programs have no unspecified behavior (i.e., their semantics are complete). Languages such as C and C++, which allow programmers to access arbitrary memory locations, are not type safe. An unsafe programming language supports operations (such as accessing arbitrary memory locations), which are not defined in terms of the language semantics. Type safety is a property of the programming language, and not of the programs themselves.