linq and entity questions

Upload: priyesh-n-pratibha

Post on 14-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 LINQ and Entity Questions

    1/26

    LINQ Interview Questions

    What is LINQ?

    LINQ, or Language INtegrated Query, is a set of classes added to the .NET Framework 3.5.LINQ adds a rich, standardized query syntax to .NET programming languages that allows

    developers to interact with any type of data.

    What are the advantages of using LINQ or Language INtegrated Query?

    In any data driven application, you get data either from a Database, or an XML file or fromcollection classes. Prior to LINQ, working with each data source requires writing a different style

    of code. Moreover, working with external resources like data bases, XML files involves

    communicating with that external resource in some syntax specific to that resource. To retrieve

    data from a database you need to send it a string that contains the SQL query to execute,similarly, to work with an XML document involves specifying an XPath expression in the form

    of a string. The idea is that using LINQ you can work with disparate data sources using a similar

    style without having to know a separate syntax for communicating with the data source (e.g.,SQL or XPath) and without having to resort to passing opaque strings to external resources.

    In any data driven web application or windows application, we use database as a datasource forthe application. In order to get data from the database and display it in a web or windows

    application, we typically do the following.

    1. Prepare your SQL Statements.

    2. Execute SQL Statements against the database.

    3. Retrieve the results.4. Populate the Business Objects.

    5. Display the Data in the Web Form or Windows From.

    publicList GetCustomerByCity(intCityId){

    //Connection String = "";stringconnStr = "";

    //Prepare the connection object and connect to the databaseSqlConnection conn = newSqlConnection(connStr);

    //Open Connectionconn.Oepn();

    //Prepare Querystringquery = "SELECT * FROM Customers WHERE CityId = @CityId";

    //Define command object with parametersSqlCommand comd = newSqlCommand(query, conn);comd.Parameters.AddWithValue("@CityId", CityId);

  • 7/30/2019 LINQ and Entity Questions

    2/26

    //Get the DataReaderSqlDataReader reader = comd.ExecuteReader();

    //Populate list of customersList customersList = newList();While(reader.Read())

    { Customer cust = newCustomer();cust.Id = reader["Id"].ToString();cust.Name = reader["Name"].ToString();customersList.Add(cust);

    }

    //Close Everythingreader.Close();conn.Close();

    //Return customer listreturncustomersList;

    }

    In order to send a query to the database we must first establish a connection to the database. Wethen must encode the logicthe SQL query, its parameters, and the parameters values into

    strings that are supplied to the SqlCommand object. And because these inputs are encoded into

    opaque strings, there is no compile-time error checking and very limited debugging support. Forexample, if there is a spelling mistake in the SELECT query causing the Customers table name

    to be misspelled, this typographical error wont show up until runtime when this page is viewed

    in a web browser. These typographical errors are easy to make as there is no IntelliSense support.

    When we use LINQ, Visual Studio would display an error message alerting us about theincorrect table name.

    Another mismatch between the programming language and the database is that the data returned

    by the database is transformed for us into objects accessible through the SqlDataReader, but

    these objects are not strongly-typed objects like wed like. To get this data into strongly-typed

    objects we must write code ourselves that enumerates the database results and populates eachrecord into a corresponding object.

    LINQ was designed to address all these issues. LINQ also offers a unified syntax for working

    with data, be it data from a database, an XML file, or a collection of objects. With LINQ you

    dont need to know the intricacies of SQL, the ins and outs of XPath, or various ways to work

    with a collection of objects. All you need be familiar with is LINQs classes and the associatedlanguage enhancements centered around LINQ.

    In other words, LINQ provides type safety, IntelliSense support, and compile-time errorchecking, and enhanced debugging scenarios when working with different datasources.

    What are the three main components of LINQ or Language INtegrated Query?

  • 7/30/2019 LINQ and Entity Questions

    3/26

    1. Standard Query Operators

    2. Language Extensions

    3. LINQ Providers

    How are Standard Query Operators implemented in LINQ?

    Standard Query Operators are implemented as extension methods in .NET Framework. TheseStandard Query Operators can be used to work with any collection of objects that implements the

    IEnumerable interface. A class that inherits from the IEnumerable interface must provide an

    enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable.Also, most of the generic collection classes implement IEnumerable interface.

    How are Standard Query Operators useful in LINQ?

    Standard Query Operators in LINQ can be used for working with collections for any of the

    following and more.1. Get total count of elements in a collection.

    2. Order the results of a collection.3. Grouping.

    4. Computing average.5. Joining two collections based on matching keys.

    6. Filter the results

    List the important language extensions made in C# to make LINQ a reality?

    1. Implicitly Typed Variables

    2. Anonymous Types

    3. Object Initializers

    4. Lambda Expressions

    What is the purpose of LINQ Providers in LINQ?

    LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method

    that executes an equivalent query against a specific data source.

    What are the four LINQ Providers that .NET Framework ships?

    1. LINQ to ObjectsExecutes a LINQ query against a collection of objects

    2. LINQ to XMLExecutes an XPATH query against XML documents

    3. LINQ to SQLExecutes LINQ queries against Microsoft SQL Server.4. LINQ to DataSetsExecutes LINQ queries against ADO.NET DataSets.

    Write a program using LINQ to find the sum of first 5 prime numbers?

    Class Sample{

    staticvoidMain(){

  • 7/30/2019 LINQ and Entity Questions

    4/26

    int[] primeNum = {1, 2, 3, 5, 7};

    //Use Count() and Sum() Standard Query OperatorsConsole.WriteLine("The Sum of first {0} prime numbers is {1}",

    primeNum.Count(), primeNum.Sum());}

    }

    What is Lambda Expression?

    A Lambda expression is nothing but an Anonymous Function, can contain expressions and

    statements. Lambda expressions can be used mostly to create delegates or expression tree types.

    Lambda expression uses lambda operator => and read as goes to operator.

    Left side of this operator specifies the input parameters and contains the expression or statement

    block at the right side.

    Example: myExp = myExp/10;

    Now, let see how we can assign the above to a delegate and create an expression tree:

    delegateintmyDel(intintMyNum);staticvoidMain(string[] args){

    //assign lambda expression to a delegate:myDel myDelegate = myExp => myExp / 10;intintRes = myDelegate(110);Console.WriteLine("Output {0}", intRes);Console.ReadLine();

    //Create an expression tree type//This needs System.Linq.ExpressionsExpression myExpDel = myExp => myExp /10;

    }

    Note: The => operator has the same precedence as assignment (=) and is right-associative.

    Lambdas are used in method-based LINQ queries as arguments to standard query operator

    methods such as Where.

    How LINQ is beneficial than Stored Procedure?

    There are couple of advantage of LINQ over stored procedures.

    1. DebuggingIt is really very hard to debug the Stored procedure but as LINQ is part of .NET,

    you can use visual studios debugger to debug the queries.

    2. DeploymentWith stored procedures, we need to provide an additional script for stored

    procedures but with LINQ everything gets complied into single DLL hence deployment becomeseasy.

  • 7/30/2019 LINQ and Entity Questions

    5/26

    3. Type SafetyLINQ is type safe, so queries errors are type checked at compile time. It is

    really good to encounter an error when compiling rather than runtime exception!

    Why Select Clause comes after From Clause in LINQ Query?

    The reason is, LINQ is used with C# or other programming languages, which requires all thevariables to be declared first. From clause of LINQ query just defines the range or conditions to

    select records. So thats why from clause must appear before Select in LINQ.

    What is the extension of the file, when LINQ to SQL is used?

    The extension of the file is .dbml.

    What is the use of System.Data.DLinq.dll?

    System.Data.DLinq.dll provides functionality to work with LINQ to SQL.

    What is the use of System.XML.XLinq.dll?

    System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.

    Which assembly represents the core LINQ API?

    System.Query.dll assembly represents the core LINQ API.

    What is the benefit of using LINQ on Dataset?

    The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.

    Suppose we want to combine the results from two Datasets, or we want to take a distinct value

    from the Dataset, then it is advisable to use LINQ.

    Normally you can use the SQL queries to run on the database to populate the Dataset, but you

    are not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to

    use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of queryingthe Dataset and provides some new features as compared to ADO.NET.

    What is the disadvantage of LINQ over stored procedures?

    The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are

    precompiled. In case of LINQ the queries need to be compile before the execution. So according

    to this, I can say stored procedures are faster in performance as compared to LINQ.

    What are Quantifiers?

    They are LINQ Extension methods which return a Boolean value

  • 7/30/2019 LINQ and Entity Questions

    6/26

    1)All

    2)Any

    3)Contains4)SequenceEqual

    example:

    int[] arr={10,20,30};var b=arr.All(a=>a>20);

    -Output:

    b will return False since all elements are not > 20.

    Difference between XElement and XDocument

    Both are the classes defined by System.Xml.Linq namespace

    XElement class represents an XML fragmentXDocument class represents an entire XML document with all associated meta-data.

    example:

    XDocument d = newXDocument(newXComment("hello"),newXElement("book",newXElement("bookname", "ASP.NET"),newXElement("authorname", "techmedia"));

    Briefly can you explain the purpose of LINQ providers in LINQ ?

    They are a set of classes that takes a LINQ query and dynamically generates a sql query which is

    executed against a specific data source(sql database, oracle, xml file, arrayetc)

    Why var keyword is used and when it is the only way to get query result?

    var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a

    generalised keyword. The compiler infers the actual type from the static type of the expression

    used to initialise the variable. One must use var with the query that returns anonymous type. E.g.

    // anonymous type returnedvar query = from w inwords

    select new{

    LetterCount = w.Length,UpperString = w.ToUpper()

    };

  • 7/30/2019 LINQ and Entity Questions

    7/26

    foreach(var item inquery){

    Console.WriteLine(item.LetterCount + " "+ item.UpperString);}

    What is Deffered Execution?

    Deferred execution means that the actual work will not be performed immediately, but rather

    when the result is requested at a latter stage. This is implemented via proxy pattern and perhaps

    yield return. The benefits of deferred executions are that potential heavy load on CPU, memoryor database is delayed to the moment it is absolutely required, therefore saving time say while

    initialisation.

    Explain Query Expression syntax, Fluent syntax, Mixed Queries.

    Query expression syntax is based on the new keywords such as from, select, join, group by, order

    by etc.

    string[] words = { "roll", "removal", "fuse", "accusation","capture", "poisoning", "accusation"};

    var query = from w inwordswhere w.Length > 4orderby w ascendingselect w;

    This query selects words with more than 4 letters and presents

    result in the ascending order. Fluent syntax is based on the regular

    C# methods that are linked in a chain, like this sample frommsdn.

    List customers = GetCustomerList();

    var customerOrders = customers.SelectMany(

    (cust, custIndex) => cust.Orders.Select(o =>

    "Customer #"+ (custIndex + 1) +" has an order with OrderID "+ o.OrderID));

    Mixed syntax means query expression syntax is mixed with fluent method calls, for example itcan be used to get the distinct values, first result or to get items as array (which by the way will

    trigger immediate query execution)

    What are Interpreted Queries?

    LINQ combines two architectural models: in-memory local and remote.

    http://msdn.microsoft.com/en-us/vcsharp/aa336758#SelectTransformationhttp://msdn.microsoft.com/en-us/vcsharp/aa336758#SelectTransformationhttp://msdn.microsoft.com/en-us/vcsharp/aa336758#SelectTransformationhttp://msdn.microsoft.com/en-us/vcsharp/aa336758#SelectTransformation
  • 7/30/2019 LINQ and Entity Questions

    8/26

    The first one is basicallyLINQ-to-Objects andLINQ-to-XML. Local model closely work with

    IEnumerable anddecoratorsequences of C# methods, lambdas and delegates. The query is

    compiled into standard imperative IL code.

    The second one isLINQ-to-SQL andLINQ-to-Entities. Remote model in contrast is rather

    declarative to the runtime. Sequences in query implement theIQueryable (which in turnderives fromIEnumerable) and after the compilation resolve into query operators from

    Queryable classexpression trees. Depending on the query provider, expression trees will be

    later interpreted by the runtime and are friendly to the remote data source.

    Use of IQueryable and IEnumerable interfaces.

    IEnumerable is applicable for in-memory data querying, in contrast IQueryable allows

    remote execution, like web service or database querying. Misuse of the interface can result in

    performance and memory problems, e.g. ifIEnumerable is used instead ofIQueryableto perform paging all the rows from data source will be loaded, instead of only those rows from

    the current page.

    Will there be any issues adding a table without primary keys to a data model?

    Every entity must have a key, even in the case where the entity maps to a view. When you usethe Entity Designer to create or update a model, the classes that are generated inherit from

    EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add it

    to the data model.

    How do you truncate a table using entity data model?

    Unfortunately Entity Framework doesnt include anything straight forward to handle this. But wecan still call a T-SQL statement using entity framework that will still minimizes the developers

    work. We can call ExecuteStoreCommand() methond on ObjectContext as shown below.

    using(var context = newMyTestDbEntities()){

    context.ExecuteStoreCommand("TRUNCATE table Dummy");}

    How do you query in entity model when the result has a join from from different database

    other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2

    ON t1.c1 = t2.c1

    As the entity model doesnt support querying from any entity other than the entities defined in

    Entity Data Model, we have to query aginst the data base using ExecuteStoredQuery of the

    context.

    Following code snippet shows how to query when other databases are joined.

    stringquery = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1= t2.c1";using(var context = newSampleEntities())

    http://www.dofactory.com/Patterns/PatternDecorator.aspxhttp://www.dofactory.com/Patterns/PatternDecorator.aspxhttp://www.dofactory.com/Patterns/PatternDecorator.aspxhttp://www.dofactory.com/Patterns/PatternDecorator.aspx
  • 7/30/2019 LINQ and Entity Questions

    9/26

    {ObjectResult records =

    context.ExecuteStoreQuery(query); foreach(DbDataRecord record inrecords){//Do whatever you want

    }}

    Can I use LINQ with databases other than SQL Server? Explain how.

    LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with otherdatabases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then

    take care of database specific operations and LINQ only needs to deal with those objects, not the

    database operations directly.

    How can we find Sequence of Items in two different array (same Type) in the same order

    using linq query?

    Public voidMatchSequenceLinq(){

    Var wordsA = {"Rahul","ashok","sweta"};Var wordsB = {"rahul","ashok","sweta"};var match = wordsA.SequenceEqual(wordsB);Console.WriteLine("The sequences match: {0}", match);

    }

    What is OfType in linq?

    publicvoidTypeofExa()

    { Var numbers = {null,1.0,"two", 3,"four",5,"six",7.0 };var doubles = from n innumbers where n isdoublen;Console.WriteLine("Numbers stored as doubles:");

    foreach(objectd indoubles){

    Console.WriteLine(d);}

    }

    Output:Numbers stored as doubles:

    17

    How can you find average of student marks from student tables (Columns are StudentID,

    Marks)?

    Public voidLinqToSqlAverage(){

  • 7/30/2019 LINQ and Entity Questions

    10/26

    var query = (from p indb. student. Marks).Average();Console.WriteLine(q);

    }

    Write a Program for Concat to create one sequence of Data Rows that contains

    DataTabless Data Rows, one after the other.

    Public voidDatasetlinq(){

    var numbersA = TestDS.Tables("NumbersA").AsEnumerable();var numbersB = TestDS.Tables("NumbersB").AsEnumerable();var allNumbers = numbersA.Concat(numbersB);Console.WriteLine("All numbers from both arrays:");

    foreach(objectn_loopVariable inallNumbers) {n = n_loopVariable;Console.WriteLine(n["number"]);

    }}

    Write a Program using Skip and Take operators. How can it beneficial for bulky data

    accessing on page?

    skip and take Operator used for Paging. Suppose we have Customer table of 100 records. To

    find 10 records by skipping the first 50 records from customer table.

    Public voidPagingdatasource (){

    Var Query =from CusDetails indb.customer skip (50) Take (10)ObjectDumper.Write(q)

    }

    Hence The LinQ SKIP operator lets you skip the results you want, and Take Operator

    enables you yo select the rest of result . So By Using Skip and Take Operator, You can createpaging of Specific sequence.

    Write small Program to generate Xml Document from table like (StudentRecord Table)

    using linq query.

    Public voidCreateXmlDocFromArray(){

    // Now enumerate over the array to build an XElement.XElement StudentRecords = newXElement("StudentInfo",from c inStudentselect newXElement("Student",newXAttribute("Name", c.Name),newXElement("RollNo", c.RollNo))

    );Console.WriteLine(StudentRecords);

    }

  • 7/30/2019 LINQ and Entity Questions

    11/26

    What are the four language extensions in C# 3.0 useful for LINQ?

    a) Lambda ExpressionsA lambda expression is an anonymous function that can be used tocreate delegates.

    b) Anonymous TypesAnonymous types are used to create a set of read-only properties into a

    single object without defining a type first.c)Object InitializersObject Initializers is a new offering in C# 3.0 to create and initialize the

    objects in one step.

    d) Implicitly Typed VariablesCan be assigned to any type.keyword used is var.

    What is the difference between OrderBy() and Sort() method over IList?

    OrderBy() sorts and gives the view IEnumerable(). But underlying list is sorted or not changed.

    Sort() modifies the underlying list.

    What is the difference between Select() and SelectMany()?

    Select() converts one type to another and returns enumerable. SelectMany() flattens the elementsand gives a combined list of elements.

    What is the difference between Skip() and SkipWhile() extension methods?

    Skip() will take an integer argument and skips the top n numbers from the given IEnumerable.SkipWhile() continues to skip the elements as long as the input condition is true. Once condition

    turns false it will return all remaining elements.

    Is the method Where() using lambda expression returns values immediately?

    Nope. It is deferred execution. It will return an object which contains the information to executethe query. The actual filtering happens when the enumeration of elements starts. The

    enumeration could be started by using a foreach loop.

    Are Where() and TakeWhile() both having same functionalities?

    No. Where() will return all elements for given condition. Take() will return elements until given

    condtion is true. Once condition turned false it exits the iteration and remaining elemments are

    not checked.

    Which is the Lambda Expression enabled extension method to check any elements satisfiesgiven condition?

    Any().

    Which is the Lambda Expression enabled extension method to check all elements satisfies

    given condition?

  • 7/30/2019 LINQ and Entity Questions

    12/26

    All().

    How to find the index of element using Where() with Lambda Expressions?

    Use the two argumented Lambda method. Where((i, ix) => i == ix);

    How does LINQ help us from the perspective of business objects?

    One of the tedious jobs in business object is parsing and searching object collections. For

    instance consider the below figure where we want to search a country by an ID value. So what

    we do is loop through the collection and get the object. Many may argue how about keeping akey in List or Array. The below example is just a sample. For instance if you want to search

    using country code and name, list / collection keys will not work with those multi-value

    searches.

    In other words using LINQ we can query business object collections and filter the collection in a

    single LINQ query.

    How can do a join using LINQ query?

    Below is the LINQ code snippet for creating joins between object collections. In this case we are

    creating a join on customer and orders. If you remember the order collection was contained in

    the customer class.

    returnfrom clsCustomer ObjCust inobjCustomerfrom clsOrder ObjOrder inObjCust.Ordersselect ObjCust;

    How can we do a group by using LINQ query?

  • 7/30/2019 LINQ and Entity Questions

    13/26

    Below is the code snippet which shows how group by query is written using LINQ. You can see

    we have created first a temp variable i.e. GroupTemp and then we have used the Select clause

    to return the same.

    var GroupCustomers = from ObjCust inobjCustomergroup ObjCust by ObjCust.City into GroupTempselect new{GroupTemp.Key,GroupTemp};

    Can we encapsulate the set and get properties for LINQ entities?

    [Table(Name = "Customer")]publicclassclsCustomerEntityWithProperties {

    privateint_CustomerId;privatestring_CustomerCode;privatestring_CustomerName;

    [Column(DbType = "nvarchar(50)")]

    publicstringCustomerCode{set{

    _CustomerCode = value;}get{

    return_CustomerCode;}

    }

    [Column(DbType = "nvarchar(50)")]publicstringCustomerName{

    set{

    _CustomerName = value;}get{

    return_CustomerName;}

    }

    [Column(DbType = "int", IsPrimaryKey = true)]publicintCustomerId{

    set{

    _CustomerId = value;}get{

    return_CustomerId;}

  • 7/30/2019 LINQ and Entity Questions

    14/26

    }}

    How can we execute stored procedures using LINQ?

    Step 1:- Create a stored procedure

    Below is the stored procedure which we will be used to flourish LINQ objects.

    Create PROCEDURE dbo.usp_SelectCustomerAS

    Select CustomerId,CustomerCode,CustomerName from Customer

    RETURN

    Step 2:- Create the LINQ Entity

    The above stored procedure returns CustomerId,CustomerCode, and CustomerName , so we

    need to prepare a LINQ entity as per the returning stored procedure data.

    [Table(Name = "Customer")]publicclassclsCustomerEntityWithProperties {

    privateint_CustomerId;privatestring_CustomerCode;privatestring_CustomerName;

    [Column(DbType = "nvarchar(50)")]publicstringCustomerCode{

    set{

    _CustomerCode = value;}get{

    return_CustomerCode;}

    }

    [Column(DbType = "nvarchar(50)")]publicstringCustomerName{

    set{

    _CustomerName = value;}get{

    return_CustomerName;}

    }

  • 7/30/2019 LINQ and Entity Questions

    15/26

    [Column(DbType = "int", IsPrimaryKey = true)]publicintCustomerId{

    set{

    _CustomerId = value;}get{

    return_CustomerId;}

    }}

    Step 3 :- Inherit from DataContext class

    In order to execute stored procedures LINQ has provided ExecuteMethod call function which

    belongs to DataContext class. This function returns ISingleresult of an entity collection. The

    ExecuteMethod call function is a protected function and can only be invoked through

    inheritance. Methods and functions from which we call our stored procedures normally formsour DAL. In other words the ExecuteMethod should be a part of our DAL.

    As said the function is purely protected you can only invoke the same by inheritance and not

    aggregation. I am really not sure why this compulsion is put by Microsoft , so in other words we

    need to create one more extra class which inherits from DataContext and then put in thecorresponding function calls for stored procedures. So below is the code snippet where we have

    inherited from DataContext class and created a new DAL class called as ClsMyContext.

    publicclassclsMyContext : DataContext{}

    Step 4:- Attribute using Function attribute

    We have created GetCustomerAll function which is attributed with Function attribute from

    System.Data.Linq.Mapping namespace. The Function attribute has a name parameter which

    specifies the stored procedure name; currently the stored procedure is usp_SelectCustomer asdefined in the previous steps.

    The IsComposable parameter defines whether this method call is for stored procedure or UDFi.e. User defined function. If IsComposable is false that means its a stored procedure and in

    case it is true that means its a user defined function.

    [Function(Name = "usp_SelectCustomer", IsComposable = false)]publicISingleResult getCustomerAll(){}

    Step 5:- Invoke Executemethod call

  • 7/30/2019 LINQ and Entity Questions

    16/26

    Ok now its time to fill in the empty function GetCustomerAll. Below is the code snippet of

    how to execute the ExecuteMethod call. This invocation returns back IExecuteResult object.

    IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));

    The object returned from IExecuteResult has ReturnValue property from which we can getresults collection of ClsCustomerEntity type.

    ISingleResult objresults =(ISingleResult) objResult.ReturnValue;

    Below is the complete code snippet with the function.

    [Function(Name = "usp_SelectCustomer", IsComposable = false)]publicISingleResult getCustomerAll(){

    IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));

    ISingleResult objresults =(ISingleResult) objResult.ReturnValue;returnobjresults;

    }

    Step 6:- Finally we call the data context in client

    So at the final step we just create the context object , call our function and loop through the

    object collection display data.

    clsMyContext objContext = newclsMyContext(strConnectionString); foreach(var row inobjContext.getCustomerAll()) {

    Response.Write(row.CustomerCode); }

    How can we handle concurrency in LINQ?

    LINQ gives three ways by which we can handle concurrency conflicts. To handle concurrency

    conflicts we need to wrap the LINQ to SQL code in a TRY block and catch the

    ChangeConflictException. We can then loop through the ChangeConflicts collection tospecify how we want the conflict to be resolved.

    catch(ChangeConflictException ex){

    foreach(ObjectChangeConflict objchangeconf inobjContext.ChangeConflicts)

    {objchangeconf.Resolve(RefreshMode.OverwriteCurrentValues);

    }}

  • 7/30/2019 LINQ and Entity Questions

    17/26

    There are 3 ways provided by LINQ system to handle concurrency conflicts:-

    KeepCurrentValues :- When this option is specified and concurrency conflicts happen LINQ

    keeps call the LINQ entity object values as it is and does not push the new values from thedatabase in to the LINQ object.

    OverwriteCurrentValues :- When this option is specified the current LINQ object data is

    replaced with the database values. KeepChanges :- This is the most weird option but can be helpful in some cases. When we talkabout classes it can have many properties. So properties which are changed are kept as it is but

    the properties which are not changed are fetched from the database and replaced.

    We need to use the RefereshMode to specify which options we need.

    What other features are provided by LINQ to fine tuning concurrency at field level?

    One of the best options provided by LINQ concurrency system is control of concurrencybehavior at field level. There are three options we can specify using the UpdateCheck attribute:

    -

    Never:- Do not use this field while checking concurrency conflicts.

    Always:- This option specifies that always use this field to check concurrency conflicts.

    WhenChanged:- Only when the member value has changed then use this field to detectconcurrency conflicts.

    Below is the code snippet which show how we can use the UpdateCheck attribute to controlproperty / field level concurrency options as specified above.

    [Column(DbType = "nvarchar(50)",UpdateCheck=UpdateCheck.Never)]publicstringCustomerCode{

    set{

    _CustomerCode = value;}get{

    return_CustomerCode;}

    }

    What kind of error reporting options are provided by LINQ when concurrency conflict

    occurs?

    LINQ concurrency system lets you specify how you want the conflicts to be reported. LINQ

    system has given 2 ways to report conflicts:-

    ContinueOnConflict:- This option says to the LINQ engine that continue even if there are

    conflicts and finally return all conflicts at the end of the process.

    FailOnFirstConflict:- This option says stop as soon as the first conflict occurs and return all the

  • 7/30/2019 LINQ and Entity Questions

    18/26

    conflicts at that moment. In other words LINQ engine does not continue ahead executing the

    code.

    Both these options can be provided as an input in SubmitChanges method using the

    ConflictMode enum. Below is the code snippet of how to specify conflict modes.

    objContext.SubmitChanges(ConflictMode.ContinueOnConflict);

    What are compiled queries?

    LINQ has provided something called as compiled LINQ queries. In compiled LINQ queries the

    plan is cached in a static class. As we all know that static class is global cache. So LINQ uses thequery plan from the static class object rather than building the preparing the query plan from

    scratch.

    Figure:LINQ Query Caching

    In all there are 4 steps which need to be performed right from the time LINQ queries are built till

    they are fired. By using compiled LINQ queries the 4 steps are reduced to 2 steps.

  • 7/30/2019 LINQ and Entity Questions

    19/26

    Figure:Query plan bypasses many steps

    What are the different steps involved to write compiled LINQ queries?

    The first thing is to import Data.Linq namespace.

    Import namespaceusingSystem.Data.Linq;

    The syntax to write compiled queries is a bit cryptic. So let us break those syntaxes in smallpieces and then we will try to see how the complete syntax looks like. To execute a compiled

    function we need to write function to pointer. This function should be static so that LINQ enginecan use the query plan stored in those static class objects.

    Below is how we define the function it starts with public static stating that this function is

    static. Then we use the Func keyword to define the input parameters and output parameters.Below is how the parameter sequence needs to be defined:-

    The first parameter should be a data context. So we have defined the data type as

    DataContext. Followed by 1 or many input parameters currently we have only one i.e. customer code so wehave defined the second parameter data type as string.

    Once we are done with all input parameters we need to define the data type of the output.

    Currently we have defined the output data type as IQueryable.

    We have given a name to this delegate function as getCustomers.

    publicstaticFunc getCustomers

  • 7/30/2019 LINQ and Entity Questions

    20/26

    We need to call method Compiled of static class CompiledQuery with the datacontext object

    and necessary define input parameters followed by the LINQ query. For the below snippet we

    have not specified the LINQ query to minimize complications.

    CompiledQuery.Compile((DataContext db, stringstrCustCode)=> Your LINQ Query);

    So now uniting the above two code snippets below is how the complete code snippet looks like.

    publicstaticFuncgetCustomers=CompiledQuery.Compile((DataContext db, stringstrCustCode)=> Your LINQ Query);

    We then need to wrap this static function in a static class. So we have taken the above defined

    function and wrapped that function in a static class clsCompiledQuery.

    publicstaticclassclsCompiledQuery{

    publicstaticFunc getCustomers =CompiledQuery.Compile((DataContext db,

    stringstrCustCode)=> from objCustomer indb.GetTable()

    where objCustomer.CustomerCode == strCustCodeselect objCustomer);

    }

    Consuming the compiled query is pretty simple; we just call the static function. Currently thisfunction is returning data type as IEnumerable.So we have to define an IEnumerable

    customer entity which will be flourished through the getCustomers delegate function. We canloop through the customer entity using clsCustomerEntity class.

    IQueryable objCustomers =clsCompiledQuery.getCustomers(objContext, txtCustomerCode.Text);foreach(clsCustomerEntity objCustomer inobjCustomers){

    Response.Write(objCustomer.CustomerName + "
    ");}

    Entity Framework Interview Questions

    What is Entity Framework?

    Entity Framework is an additional layer between application and database that enables thedevelopers to program against the conceptual application model instead of programming directly

    against the relational storage schema.

    Will there be any issues adding a table without primary keys to a data model?

  • 7/30/2019 LINQ and Entity Questions

    21/26

    Every entity must have a key, even in the case where the entity maps to a view. When you use

    the Entity Designer to create or update a model, the classes that are generated inherit from

    EntityObject, which requires EntityKey. So, we have to have a primary key in the table to add itto the data model.

    How do you truncate a table using entity data model?

    Unfortunately Entity Framework doesnt include anything straight forward to handle this. But we

    can still call a T-SQL statement using entity framework that will still minimizes the developerswork. We can call ExecuteStoreCommand() methond on ObjectContext as shown below.

    using(var context = newMyTestDbEntities()){

    context.ExecuteStoreCommand("TRUNCATE table Dummy");}

    How do you query in entity model when the result has a join from from different database

    other than the entity model? E.g.: SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2ON t1.c1 = t2.c1

    As the entity model doesnt support querying from any entity other

    than the entities defined in Entity Data Model, we have to query aginst the data base usingExecuteStoredQuery of the context.

    Following code snippet shows how to query when other databases are joined.

    stringquery = "SELECT t1.c1, t2.c2 FROM table1 AS t1 JOIN table2 t2 ON t1.c1= t2.c1";using(var context = newSampleEntities()){

    ObjectResult records =context.ExecuteStoreQuery(query);

    foreach(DbDataRecord record inrecords){//Do whatever you want

    }}

    What is minimum requirement for Entity Framework applications to run?

    The Entity Framework is a component of the .NET Framework so Entity

    Framework applications can run on any computer on which the .NETFramework starting with version 3.5 SP1 is installed.

    What is CSDL?

    Conceptual schema definition language (CSDL) is an XML-based languagethat describes the entities, relationships, and functions that make up a conceptual model of a

  • 7/30/2019 LINQ and Entity Questions

    22/26

    data-driven application. This conceptual model can be used by the Entity Framework or WCF

    Data Services.

    The metadata that is described with CSDL is used by the Entity

    Framework to map entities and relationships that are defined in a

    conceptual model to a data source.More=> http://msdn.microsoft.com/en-us/library/bb399292.aspx

    What is SSDL?

    Store schema definition language (SSDL) is an XML-based language thatdescribes the storage model of an Entity Framework application.

    In an Entity Framework application, storage model metadata is loaded from a .ssdl file (written

    in SSDL) into an instance of the System.Data.Metadata.Edm.StoreItemCollection and isaccessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The

    Entity Framework uses storage model metadata to translate queries against the conceptual modelto store-specific commands.More=> http://msdn.microsoft.com/en-us/library/bb399559.aspx

    What is MSL?

    Mapping specification language (MSL) is an XML-based language that describes the mappingbetween the conceptual model and storage model of an Entity Framework application.

    In an Entity Framework application, mapping metadata is loaded from an .msl file (written in

    MSL) at build time. The Entity Framework uses mapping metadata at runtime to translate

    queries against the conceptual model to store-specific commands.More=> http://msdn.microsoft.com/en-us/library/bb399202.aspx

    What is Entity Data Model?

    The Entity Data Model (EDM) is a set of concepts that describe the structure of data, regardless

    of its stored form. The EDM borrows from the Entity-Relationship Model described by Peter

    Chen in 1976, but it also builds on the Entity-Relationship Model and extends its traditional uses.

    The EDM addresses the challenges that arise from having data stored in many forms. For

    example, consider a business that stores data in relational databases, text files, XML files,

    spreadsheets, and reports. This presents significant challenges in data modeling, applicationdesign, and data access. When designing a data-oriented application, the challenge is to write

    efficient and maintainable code without sacrificing efficient data access, storage, and scalability.

    When data has a relational structure, data access, storage, and scalability are very efficient, butwriting efficient and maintainable code becomes more difficult. When data has an object

    structure, the trade-offs are reversed: Writing efficient and maintainable code comes at the cost

    of efficient data access, storage, and scalability. Even if the right balance between these trade-offs can be found, new challenges arise when data is moved from one form to another. The

  • 7/30/2019 LINQ and Entity Questions

    23/26

    Entity Data Model addresses these challenges by describing the structure of data in terms of

    entities and relationships that are independent of any storage schema. This makes the stored form

    of data irrelevant to application design and development. And, because entities and relationshipsdescribe the structure of data as it is used in an application (not its stored form), they can evolve

    as an application evolves.

    More=> http://msdn.microsoft.com/en-us/library/ee382825.aspx

    Which are the key concepts of Entity Data Model?

    The Entity Data Model (EDM) uses three key concepts to describe the structure of data: entity

    type, association type, and property. These are the most important concepts in describing the

    structure of data in any implementation of the EDM.

    1. Entity Type: The entity type is the fundamental building block for describing the structure of

    data with the Entity Data Model. In a conceptual model, entity types are constructed fromproperties and describe the structure of top-level concepts, such as a customers and orders in a

    business application.

    2. Association Type: An association type (also called an association) is the fundamental

    building block for describing relationships in the Entity Data Model. In a conceptual model, an

    association represents a relationship between two entity types (such as Customer and Order).

    3. Property: Entity types contain properties that define their structure and characteristics. For

    example, a Customer entity type may have properties such as CustomerId, Name, and Address.More=> http://msdn.microsoft.com/en-us/library/ee382840.aspx

    What is .edmx file and what it contains?

    An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping

    between these models. An .edmx file also contains information that is used by the ADO.NETEntity Data Model Designer (Entity Designer) to render a model graphically.

    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.

    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.

    What is use of EntityDataSource Control?

  • 7/30/2019 LINQ and Entity Questions

    24/26

    The ADO.NET EntityDataSource control supports data binding scenarios in Web applications

    that use the ADO.NET Entity Framework. Like the Entity Framework, the control is available as

    part of the .NET Framework 3.5, beginning with SP1. Like the other Web server data sourcecontrols, the EntityDataSource control manages create, read, update, and delete operations

    against a data source on behalf of data-bound controls on the same page. The EntityDataSource

    works with editable grids, forms with user-controlled sorting and filtering, dually bound drop-down list controls, and master-detail pages.more=>http://msdn.microsoft.com/en-us/library/cc488502.aspx

    What is Model First Approach?

    A new Model First approach was supported in Visual Studio 2010, which was released togetherwith the second Entity Framework version (Entity Framework v4). In Model First approach the

    development starts from scratch. At first, the conceptual model is created with Entity Data Model

    Designer, entities and relations are added to the model, but mapping is not created.

    After this Generate Database Wizard is used to generate storage (SSDL) and mapping (MSL)parts from the conceptual part of the model and save them to the edmx file. Then the wizard

    generates DDL script for creating database (tables and foreign keys)

    If the model was modified, the Generate Database Wizard should be used again to keep themodel and the database consistent. In such case, the generated DDL script contains DROPstatements for

    tables, corresponding to old SSDL from the .edmx file, and CREATE statements for tables,

    corresponding to new SSDL, generated by the wizard from the conceptual part. In Model Firstapproach developer should not edit storage part or customize mapping, because they will be re-

    generated each time when Generate Database Wizard is launched.

    What is Code First Approach?

    Code First allows you to define your model using C# or VB.Net classes, optionally additional

    configuration can be performed using attributes on your classes and properties or by using a

    Fluent API. Your model can be used to generate a database schema or to map to an existing

    database.More=>http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx

    What is Entity SQL?

    Entity SQL is a SQL-like storage-independent language, designed to query and manipulate richobject graphs of objects based on the Entity Data Model (EDM).More=>http://msdn.microsoft.com/en-us/library/bb399560(v=vs.90).aspx

    What is LINQ To Entities?

    LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities.

  • 7/30/2019 LINQ and Entity Questions

    25/26

    LINQ to Entities enables developers to write queries against the database using one of the

    supported .NET Framework programming languages such as Visual Basic or Visual C#.

    More=>http://msdn.microsoft.com/en-us/library/bb386964(v=vs.90).aspx

    What is EntityClient?

    System.Data.EntityClient is a storage-independent ADO.NET data provider that contains classes

    such as EntityConnection, EntityCommand, and EntityDataReader. Works with Entity SQL and

    connects to storage specific ADO.NET data providers, such as SqlClient.More=>http://msdn.microsoft.com/en-us/library/bb738561(v=vs.90).aspx

    What is Deferred Loading(Lazy Loading)?

    When objects are returned by a query, related objects are not loaded at the same time.

    Instead they are loaded automatically when the navigation property is accessed. Also known as

    lazy loading,More=>http://msdn.microsoft.com/en-us/library/dd196179(v=vs.90).aspx

    What is Eager Loading?

    The process of loading a specific set of related objects along with the objects that were explicitly

    requested in the query.More=>http://msdn.microsoft.com/en-us/library/bb896272(v=vs.90).aspx

    What is Complex Type?

    A .NET Framework class that represents a complex property as defined in the conceptual model.Complex types enable scalar properties to be organized within entities. Complex objects areinstances of complex types.

    More=>http://msdn.microsoft.com/en-us/library/bb738472(v=vs.90).aspx

    What is Conceptual Model?

    An implementation of the Entity Data Model (EDM), specific to the Entity Framework, whichrepresents an abstract specification for the data structures that define an entity-relationship

    representation of data in the domain of an application.

    More=>http://msdn.microsoft.com/en-us/library/bb399183(v=vs.90).aspx

    What is use of Entity Container?

    Specifies entity sets and association sets that will be implemented in a specified namespace.

    More=>http://msdn.microsoft.com/en-us/library/bb399557(v=vs.90).aspx

    What is Explicit Loading?

  • 7/30/2019 LINQ and Entity Questions

    26/26

    When objects are returned by a query, related objects are not loaded at the same time. By default,

    they are not loaded until explicitly requested using the Load method on a navigation property.

    More=>http://msdn.microsoft.com/en-us/library/dd196179(v=vs.90).aspx

    What do you mean by Navigation Property?

    A property of an entity type that represents a relationship to another entity type, as defined by an

    association. Navigation properties are used to return related objects as an EntityCollection or an

    EntityReference, depending on the multiplicity at the other end of the association.More=>http://msdn.microsoft.com/en-us/library/bb399562(v=vs.90).aspx

    What is scalar property?

    A property of an entity that maps to a single field in the storage model.

    What is split entity?

    An entity type that is mapped to two separate types in the storage model.

    What do you mean by table-per-hierarchy?

    A method of modeling a type hierarchy in a database that includes the attributes of all the typesin the hierarchy in one table.

    More=>http://msdn.microsoft.com/en-us/library/bb738443(v=vs.90).aspx

    What do you mean by table-per-type?

    A method of modeling a type hierarchy in a database that uses multiple tables with one-to-onerelationships to model the various types.

    More=>http://msdn.microsoft.com/en-us/library/bb738685(v=vs.90).aspx