LINQ interview questions for experienced

Update Record in Entity Framework?

We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to do is attach/add it to the context. Set its State as Modified and then call the SaveChanges But we need to be careful in a disconnected scenario as the update will update all the fields, Hence a chance of accidentally overwriting a field. We also show you how to update multiple records & Related Data etc.

Disconnected ex:

private void UpdateConnected()

{

    Department dep;

    //Connected Scenario

    using (EFContext db = new EFContext())

    {

        db.Database.Log = Console.WriteLine;

        dep = db.Departments.Where(d => d.Name == "Accounts").First();

        dep.Descr = "This is Accounts Department";

        db.SaveChanges();

        Console.WriteLine("Department {0} ({1}) is Modified ", dep.Name, dep.DepartmentID);

        Console.ReadKey();

    }

}

Connected Ex:

private void updateDepartment2(int id, string descr)

{

    using (EFContext db = new EFContext())

    {

        db.Database.Log = Console.WriteLine;

        Department dep = db.Departments.Where(f => f.DepartmentID == id).FirstOrDefault();

        if (dep == null) throw new Exception("");

        dep.Descr = descr;

        db.SaveChanges();

    }

    Console.WriteLine("Department {0} ({1}) is Updated ", dep.Name, dep.DepartmentID);

    Console.ReadKey();

}

Multiple Records:

private void UpdateMultipleRecords()

{

    List<Department> deps = new List<Department>();

    deps.Add(new Department { DepartmentID = 1, Descr = "Sales" });

    deps.Add(new Department { DepartmentID = 2, Descr = "Purchase" });

    deps.Add(new Department { DepartmentID = 3, Descr = "HR" });

    using (EFContext db = new EFContext())

    {

        db.Database.Log = Console.WriteLine;

        foreach (var item in deps)

        {

            var dept = db.Departments.Where(f => f.DepartmentID == item.DepartmentID).FirstOrDefault();

            if (dept == null) throw new Exception("");

            dept.Descr = item.Descr;

        }

        db.SaveChanges();

    }

    Console.WriteLine("Records Updated ");

    Console.ReadKey();

}

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

Eager Loading in Entity Framework

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method.In the following example, it gets all the students from the database along with its standards using the Include() method.

LINQ Query Syntax:

using (var context = new SchoolDBEntities())

{

    var stud1 = (from s in context.Students.Include("Standard")

                where s.StudentName == "Bill"

                select s).FirstOrDefault<Student>();

}

LINQ Method Syntax:

using (var ctx = new SchoolDBEntities())

{

    var stud1 = ctx.Students

                   .Include("Standard")

                   .Where(s => s.StudentName == "Bill")

                   .FirstOrDefault<Student>();

}

Use Lambda Expression

You can also use the LINQ lambda expression as a parameter in the Include method. For this, take a reference of System.Data.Entity namespace and use the lambda expression as shown below:

using System;

using System.Data.Entity;

class Program

{

    static void Main(string[] args)

    {

        using (var ctx = new SchoolDBEntities())

        {

            var stud1 = ctx.Students.Include(s => s.Standard)

                            .Where(s => s.StudentName == "Bill")

                            .FirstOrDefault<Student>();

        }

    }

}

Load Multiple Entities

You can also eagerly load multiple levels of related entities. The following example query eagerly loads the Student, Standard and Teacher entities:

using (var ctx = new SchoolDBEntities())

{

    var stud1 = ctx.Students.Include("Standard.Teachers")

                    .Where(s => s.StudentName == "Bill")

                    .FirstOrDefault<Student>();

}

Or use the lambda expression as below:

using (var ctx = new SchoolDBEntities())

{

    var stud1 = ctx.Students.Include(s => s.Standard.Teachers)

                    .Where(s => s.StudentName == "Bill")

                    .FirstOrDefault<Student>();

}

Lazy Loading in Entity Framework

Lazy loading is delaying the loading of related data, until you specifically request for it. It is the opposite of eager loading. For example, the Student entity contains the StudentAddress entity. In the lazy loading, the context first loads the Student entity data from the database, then it will load the StudentAddress entity when we access the StudentAddress property as shown below.

using (var ctx = new SchoolDBEntities())

{

    //Loading students only

    IList<Student> studList = ctx.Students.ToList<Student>();

 

    Student std = studList[0];

 

    //Loads Student address for particular Student only (seperate SQL query)

    StudentAddress add = std.StudentAddress;

}

Disable Lazy Loading

We can disable lazy loading for a particular entity or a context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.

public partial class SchoolDBEntities : DbContext

{

    public SchoolDBEntities(): base("name=SchoolDBEntities")

    {

        this.Configuration.LazyLoadingEnabled = false;

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

    {

    }

}

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.

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

LINQ provides element operators which return a single element or a specific element from a collection. The elements operators are Single, SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault.

Single

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection.

SingleOrDefault

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if more than one match found for that element in the collection. A default value is returned, if no match is found for that element in the collection.

List<int> data = new List<int> { 10, 20, 30, 40, 50 };

//Try to get element at specified position

Console.WriteLine(data.ElementAt(1)); //result:20

//Try to get element at specified position if exist, else returns default value

Console.WriteLine(data.ElementAtOrDefault(10)); //result:0, since default value is 0

Console.WriteLine(data.First()); //result:10

Console.WriteLine(data.Last()); //result:50

//try to get first element from matching elements collection

Console.WriteLine(data.First(d => d <= 20)); //result:10

//try to get first element from matching elements collection else returns default value

Console.WriteLine(data.SingleOrDefault(d => d >= 100)); //result:0, since default value is 0

//Try to get single element

// data.Single(); //Exception:Sequence contains more than one element

//Try to get single element if exist otherwise returns default value

// data.SingleOrDefault(); //Exception:Sequence contains more than one element

//try to get single element 10 if exist

Console.WriteLine(data.Single(d => d == 10)); //result:10

//try to get single element 100 if exist otherwise returns default value

Console.WriteLine(data.SingleOrDefault(d => d == 100)); //result:0, since default value is 0

 

First

It returns first specific element from a collection of elements if one or more than one match found for that element. An exception is thrown, if no match is found for that element in the collection.

FirstOrDefault

It returns first specific element from a collection of elements if one or more than one match found for that element. A default value is returned, if no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault

You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:

When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.

When you want a default value is returned if the result set contains no record, use SingleOrDefault.

When you always want one record no matter what the result set contains, use First or FirstOrDefault.

When you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.
----------------------------------------
-------------------------------------------------------------------------------------


Comments

Popular posts from this blog

DOT NET CORE Basic Interview Question and Answers

Angular Basic concepts

Sql server interview questions for experienced