Can you show a simple LINQ to SQL example?

 Posted by ArticlesMaint on 9/29/2009 | Category: LINQ Interview questions | Views: 8003


So let’s first start with a simple LINQ to SQL example and then we will try to understand how we can establish relationship in LINQ entities.
 


Step 1:- Define Entity classes using LINQ
 


When we design project using tiered approach like 3-tier or N-tier we need to create business classes and objects. For instance below is a simple class which defines a class which is mapped to a country table as shown below. You can see we how the class properties are mapped in one to one fashion with the table. These types of classes are termed as entity classes.
 



In LINQ we need to first define these entity classes using attribute mappings. You need to import “System.Data.Linq.Mapping;” namespace to get attributes for mapping. Below is the code snippet which shows how the ‘Table’ attribute maps the class with the database table name ‘Customer’ and how ‘Column’ attributes helps mapping properties with table columns.
 

[Table(Name = "Customer")]

public class clsCustomerEntityWithProperties
{
private int _CustomerId;
private string _CustomerCode;
private string _CustomerName;

[Column(DbType = "nvarchar(50)")]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}

[Column(DbType = "nvarchar(50)")]
public string CustomerName
{
set
{
_CustomerName = value;
}
get
{
return _CustomerName;
}
}

[Column(DbType = "int", IsPrimaryKey = true)]
public int CustomerId
{
set
{
_CustomerId = value;
}
get
{
return _CustomerId;
}
}
}


 


Below is a more sophisticated pictorial view of the entity classes mapping with the customer table structure.
 



 


Step 2:- Use the datacontext to bind the table data with the entity objects.
 


The second step is use the data context object of LINQ to fill your entity objects. Datacontext acts like a mediator between database objects and your LINQ entity mapped classes.
 



So the first thing is to create the object of datacontext and create a active connection using the SQL connection string.



DataContext objContext = new DataContext(strConnectionString);


The second thing is to get the entity collection using the table data type. This is done using the ‘gettable’ function of the datacontext.



Table<clsCustomerEntity> objTable =
objContext.GetTable<clsCustomerEntity>();


Once we get all the data in table collection it’s time to browse through the table collection and display the record.

 

foreach (clsCustomerEntity objCustomer in objTable)

{
Response.Write(objCustomer.CustomerName + "<br>");
}

 



 


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response