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:

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:

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.

 

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:

Database First:

Code First:

---------------------------------------------------------------------------------------------------------------------------------------------------------

http://www.codeguru.com/csharp/csharp/net30/article.php/c13715/Introduction-to-LINQ-Part-2-LINQ-to-XML.htm

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

            }

        }

    }

--------------------------------------------------------------------------------------------------------------------

//To add theme in pre_init

 Page.Theme = ConfigurationManager.AppSettings["ESPL_Theme"].ToString();

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:

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:

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 (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

LINQ Joins

 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.