How to create relationships between entities in the Entity Framework Code First Approach

The Entity Framework Code First approach allows us to create a model as a plain class and then the database gets created from the domain model or entity class. In the Code First approach, the database gets created from the classes.

Some advantages of the Entity Framework Code First approach include (as stated in Scott Gu’s blog):

  • Developing without ever having to open a designer or define an XML mapping file
  • Defining your model objects by simply writing “plain old classes” with no base classes required
  • Using a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally overriding the convention-based persistence and using a fluent code API to fully customize the persistence mapping

Rather the delving more into theoretical concepts, in this post we will directly jump into code and create a table and database using the Code First approach. In this post we will learn how we can create entities and a relationship between entities in the Entity Framework Code First approach. In the EF Code First approach, there are two options to create the relationship between entities, through:-Data annotations and  Fluent API

In this post we will use data annotations to create the relationship between entities.

Create database with one table

Let us start with creating a table named Student in a database with the code first approach. The domain class Student can be created as shown in the listing below:


As you might have already noticed, the Student class is a plain class. Entity Framework will use the Student class to create the table in the database. The Student class represents the domain entity and it should not have any information or references of the database. Entity Framework will use the Student class to create the Student table.

Once the domain entity class is created, next we need to create a Context class which will inherit the DataContext class. The context class can be created as shown in the listing below:


Read the full article on the Infragistics blog

How to view the generated SQL Query of LINQ

Have you ever thought of viewing generated SQL query of LINQ you write? You may need the generated query for the debugging and the logging purposes. In this post let us see how to print the generated SQL query on the console.

Let us consider you have written LINQ as follows:

            DataClasses1DataContext context = new DataClasses1DataContext();
            IEnumerable<Order> result = context.Orders;
            var product = result.Where(x => x.OrderID == 10248);
            context.Log = Console.Out; 
            foreach(var r in product)

You can print the generated SQL by putting one line of code just before data gets loaded. In this scenario put following line of code anywhere but before the foreach statement.


You will get the generated SQL query in console as follows: clip_image001

You can set or get log of the DataContext in a TextWriter. If required you can save them on a file system etc.

Happy Coding.

What is difference between First and FirstOrDefault in LINQ?

Last week I were presenting LINQ to group of almost 100 audience. While writing query a question raised that what is difference between First and FirstOrDefault . At that time I was not very sure about answer so I asked audience to help me. One from audience answered this question. So credit of this blog to him. For benefit of all I am documenting answer below,

Let us focus on answer of this question. I am sure that you may have come across following query in LINQ.

In below query we are fetching First record on given condition.


Now there are two kind of result you can expect.

  • Either a product on basis of criteria
  • Or there is no product on given criteria

If there is no product on the critera you are searching then LINQ will throw you run time exception of type InvalidOperationException


So when you are working with First() make sure that you have handled the InvalidOperationException else you may encounter exception if there is no result matched on given criteria. So you may want to modify code as given below,

 Product result = (from r in GetProducts()
 r.ProductId == 1
 select r).First();
 catch (InvalidOperationException ex)

If there is no match then you will get output as below,


Next option is FirstOrDefault . So you may have come across following query. If there is no Product matched on given criteria then LINQ will return NULL.


So assume there is not matched Product and query has returned NULL then in that case if you access result then you will get exception as following


To avoid run time NullReferenceException you can modify code as following,

Product result1 = (from r in GetProducts()
 r.ProductId == 1
 select r).FirstOrDefault() ;
 if (result1 != null)

 Console.WriteLine("No Record Found");


Now when there is no Product code will gracefully print a message that No Record Found. This is basic difference between First and FirstOrDefualt. I hope you find this post useful. Thanks for reading.

LINQ to XML in a Nutshell

Data may exist in much form. You may have data in relational tables residing on a relational database or portable data in form of XML. Since data exist in many forms, obviously there are many ways to manipulate or access them. One of the most popular ways of sharing data is as XML.

Considering prominent presence of XML as way of data sharing, LINQ to XML got introduced in C# 3.0 to work effectively and efficiently with XML data. LINQ to XML API contains classes to work with XML. All classes of LINQ to XML are in namespace System.XML.Linq.


Objective of this article is to understand, how could we work with LINQ to XML?

Let us start with below image. It depicts an isomorphic relationship between XML elements and cross-ponding LINQ to XML classes.


XML Element is fundamental XML constructs. An Element has a name and optional attributes. An XML Elements can have nested Elements called Nodes also.

XML Element is represented by XElement class in LINQ to XML. It is defined in namespace System.Xml.Linq. And it inherits the class XContainer that derives from XNode. Below tasks can be performed using XElement class

  • It can add child element.
  • It can delete child element.
  • It can change child element.
  • It can add attributes to an element.
  • It can be used to create XML tree
  • It is used to serialize the content in a text form

XElement class got many overloaded constructors. You can pass XAttribute to create XML elements with attribute.

If you examine below code snippet, I am creating XML with root element Root and many child elements. Child Element Data1 and Data2 got attributes name and ID respectively with value Dj and U18949

Code Listing 1

XElement xmltree = new XElement("Root",
new XElement("Data1", new XAttribute("name", "Dj"), 1),
new XElement("Data2", new XAttribute("ID", "U18949"),
new XAttribute("DEPT","MIT"),2),
new XElement("Data3", "3"),
new XElement("Data4", "4")

On executing above code you should get below output,


Let us stop here and examine how Attributes of XML is mapped in XAttribute of LINQ to XML. XML Attribute is a Name/Value pair associated with XML elements. XAttribute class represents XML Attributes in LINQ to XML. XAttribute class is overloaded with two constructors. Most frequent used constructor is one takes name and values as input parameter. In CodeListing1 , attributes to element is being created using XAttribute class.

A XML tree can be constructed using XAttribute and XElement class.

Assume you have a list of Authors as below code listing, Author is a custom class.

Code Listing 2

static List<Author> CreateAuthorList()
List<Author> list = new List<Author>()
new Author(){Name="Dhananjay Kumar",NumberofArticles= 60},
new Author (){Name =" Pinal Dave ", NumberofArticles =5},
new Author () {Name = " Deepti maya patra",NumberofArticles =55},
new Author (){Name=" Mahesh Chand",NumberofArticles = 700},
new Author (){Name =" Mike Gold",NumberofArticles = 300},
new Author(){Name ="John Papa",NumberofArticles = 200},
new Author (){Name ="Shiv Prasad Koirala",NumberofArticles=100},
new Author (){Name =" Tim  ",NumberofArticles =50},
new Author (){Name=" J LibertyNumberofArticles =50}
return list;


class Author
public string Name { get; set; }
public int NumberofArticles { get; set; }

XML tree can be constructed from List of Authors as below code listing,

Code Listing 3

List<Author> list = CreateAuthorList();

XElement xmlfromlist = new XElement("Authors",
from a in list
new XElement("Author",
new XElement("Name", a.Name),
new XElement("NumberOfArticles", a.NumberofArticles)));




Above code snippet will create Authors as root element. There may be any number of Authors as child element inside root element Authors. There are two other elements Name and NumberOfArticles are in XML tree.

There may be scenario when you want to create XML tree from a SQL Server table. You need to follow below steps,

  1. Create Data Context class using LINQ to SQL class
  2. Retrieve data to parse as XML
  3. Create XML tree
  4. Create elements and attributes using XElement and XAttribute
  5. WCF is name of table.

Code Listing 4

DataClasses1DataContext context = new DataClasses1DataContext();
var res = from r in context.WCFs select r;

XElement xmlfromdb = new XElement("Employee",
from a in res
new XElement("EMP",
new XElement("EmpId", a.EmpId),
new XElement("Name", a.Name)));




By this point you know various ways of constructing XML tree and saving on file system. Now next thing come to your mind would be how to parse XML files using LINQ.

Parsing of XML document means reading XML document, identifies the function of each of the document and then makes this information available in memory for rest of the program. XElement.Parse () method is used to parse XML. This is an overloaded method. This takes a string input parameter to parse. Second overloaded method takes extra input parameter LoadOptions. LoadOption defines where to preserve space in information or not?

Below code snippet is parsing a string with space preserve.

Code Listing 5



XElement xmltree = XElement.Parse(@"<Address><Name>Dhananjay Kumar </Name> <Road> Padma Road </Road> </Address>",LoadOptions.PreserveWhitespace);

After knowing all the pieces of LINQ to XML, let us go ahead and find how we could put all information we have so far to bind information from XML file to DataGrid of Silverlight. It is a common requirement when you need to bind or display data from XML File to Silverlight Data Grid.

Essentially there are three steps you need to execute to bind XML to Silverlight Data Grid.

  1. Download content of XML file as string using WebClient class.
  2. Parse XML file using LINQ to XML
  3. Bind parsed result as item source of Data Grid.

Very first you need to prepare XML file as data source. Put XML file in bin folder of Silverlight project. However you can parse XML file from remote location as well.

We are going to bind Data.xml residing in client bin folder to Data Grid.

Code Listing 6

<?xml version="1.0" encoding="utf-8" ?>
<Student RollNumber="1" Name="John Papa" />
<Student RollNumber="2" Name="Scott Gui" />
<Student RollNumber="3" Name="Jessy Liberty" />
<Student RollNumber="4" Name="Tim Huer" />
<Student RollNumber="5" Name="Victor G" />
<Student RollNumber="6" Name="Mahesh Chand" />
<Student RollNumber="7" Name="Pinal Dave" />
<Student RollNumber="8" Name="Suprotim Agarwal" />
<Student RollNumber="9" Name="Dhananjay Kumar" />
<Student RollNumber="10" Name="Kunal Chawudhary" />
<Student RollNumber="11" Name="Abhijit Jana" />
<Student RollNumber="12" Name="Shiv Prasad Koirala" />

Next task you need to design XAML page. I am keeping it simple and putting a Button and DataGrid . On click event of button datagrid will be bind with data from xml file.

Xaml design would look like below code snippet.

Code Listing 7

<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Vertical" Margin="50,50,50,50">
<Button x:Name="btnDemo" Content="Click To get Data From  XML File" Height="62" Width="362" />
<sdk:DataGrid x:Name="grdXmlData" Height="Auto" Width="Auto" AutoGenerateColumns="True" />

On click event of button, make an asynchronous call and download the file.

Code Listing 8


private void btnDemo_Click(object sender, RoutedEventArgs e)
WebClient client = new WebClient();
Uri uritoXML = new Uri("Data.xml", UriKind.Relative);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);



Once string is downloaded, you need to parse the downloaded XML.

Code Listing 9

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

if (e.Error != null)
MessageBox.Show("There is Error Downloading Data from XML File ");



XML can be parsed as below. On examining below code, you will find XML file is loaded using XDocument. After loading file is being traversed using Descendants method. On getting the values for each Student node, you need to create instance of Student and add it to the list of Student.

Code Listing 10

void ParseXMLFile(string  dataInXmlFile)

lstStudents = new List<Student>();

XDocument xmlDoc = XDocument.Parse(dataInXmlFile);
lstStudents  = (from r in xmlDoc.Descendants("Student")
select new Student
Name = (string) r.Attribute("Name").Value,
RollNumber =(string) r.Attribute("RollNumber").Value

grdXmlData.ItemsSource = lstStudents;



  1. Function is taking string as input parameter. Here we will pass e.Result from Downloadcompletedstring event.
  2. Creating an instance of XDocument by parsing string
  3. Reading each descendants or element on Xml file and assigning value of each attribute to properties of Entity class (Student).

We need to create an Entity class to map the data from XML File. I am going to create a class Student with properties exactly as the same of attributes of Student Element in XML file.

Student class is listed as below,

Code Listing 11

public class Student

public string RollNumber { get; set; }
public string Name { get; set; }


On running you should get the expected output.

Assume you have data in XML file as below. This file is save in location d drive.


<?xml version="1.0" encoding="utf-8" ?>
<book id="bk101">
<author id="1">Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<description> An in-depth look at creating applications with XML.</description>
<book id="bk102">
<author id="2">Ralls, Kim</author>
<title>Midnight Rain</title>
<description> A former architect battles corporate zombies,an evil sorceress, and her own childhood to become queen of the world.</description>
<book id="bk103">
<author id="3">Corets, Eva</author>
<title>Maeve Ascendant</title>
<description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society. </description>

<book id="bk104">
<author id="4">Corets, Eva</author>
<title>Oberon’s Legacy</title>
<description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description>


<book id="bk105">
<author id="5">Corets, Eva</author>
<title>The Sundered Grail</title>
<description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon’s Legacy.</description>


To fetch all the Books, just you need to parse the XML file. Find the descendants book and fetch it in anonymous class.

XDocument document = XDocument.Load("D:\\Data.xml");
#region Fetch All the Books
var books = from r in document.Descendants("book")
select new
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,


foreach (var r in books)
Console.WriteLine(r.PublishDate + r.Title + r.Author);


If you want to fetch a particular book, you need to apply where condition while parsing XML file.

var selectedBook = from r in document.Descendants("book").Where
select new
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,


foreach (var r in selectedBook)
Console.WriteLine(r.PublishDate + r.Title + r.Author);


You need to fetch author Id of a particular book with Id bk102. To do that you need to select as below,

var selectedBookAttribute = (from r in document.Descendants("book").Where
(r => (string)r.Attribute("id") == "bk102")
select r.Element("author").Attribute("id").Value).FirstOrDefault();



To fetch the entire author name, you need to execute below query.

var allauthors = from r in document.Descendants("book")
select r.Element("author").Value;
foreach(var r in allauthors)


I hope this article was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter or may like Facebook page of my blog If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

ASP.Net GridView with LinqDataSource

In this post I will walkthrough on using ASP.Net Gridview with LinqDatasource.

You can bind a GridView with LinqDataSource and would able to

  1. Edit
  2. Delete
  3. View data without writing a single line of code.

To see how it works , follow the steps below;


Crate a ASP.Net Web Application.


Step 2

Right click and add a new item in ASP.Net Web Application project. Choose LINQ to SQL class from Data tab.


Drag and drop tables from Server Explorer to generate Data Context class. I am creating Data Context class from School Database by selceting Person table.


Now Data Context class has been created.

Step 3

Go ahead and drag and drom a GridView on Default.aspx page.


Switch to the design view on Default.aspx page . Select Properties of GridView by clicking on the arrow key at right top of GridView and then Choose Data Source option selcet New data source.


From the dialog box you need to choose LINQ and if you want you can edit the data source name as well. I am leaving default data source name LinqDataSource1


Next you need to choose the context object . We have already created DataContext named DataClasses1DataContext1 .Choose DataClasses1DataContext1 as context object .


After choosing context object click on Next button . From next dialog box choose table and columns you want to bind grid view . Click on the advanced button,


Since you want data in grid view editable. So go ahead and checked all the three options.


Click Ok and clcik on Finish

Step 4

Since you want to Edit, Delete and Insert data from Grid View. So open properties of GridView and enable the options by cheking the chekboxes.



You have done it . Press F5 to run the appliction. You would able to Edit, Delete and View the data in Grid View without writing a single line of code.


I hope this post was useful. Thanks for reading Smile




Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine