Monday, 23 March 2015

Conditional Mapping in EntityFramework

Conditional mapping in Entity Framework means When we want only a portion of data From database or table according to a condition then for fulfil this situation we use Conditional Mapping in EntityFramework.
What is Conditional Mapping
Conditional mapping is a condition that Allow us to filter the result  that comes from the database for a entity. It Also enforces that an entity is mapped to data in the database With a particular conditions which are given in the conditional mapping. For using conditional mapping in Entity, we have to Right click on entity and click on Table mapping. There we can <Add a Condition>
As Shown below

When we add a condition, that condition will be added to query that we will change to the database.
Available Conditional Mappings Operators
In Conditional mapping there are two type of operators. First one is “equality (=)” and other one “ Is” operator. The equality operator (=) have values of  integers or strings . The Is operator have Null or Not Null
Conditional Mapping Example
Step(1)
In Conditional mapping example we will use Students table with a extra column with the name “ IsDiscard”  Throw this we will see that particular student is Discard or not.
Create table Students
(
     StudentID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50),
     IsDiscard bit not null
)

Insert into Students values ('Munesh', 'Sharma', Male',0)
Insert into Students values ('Rahul', 'Sharma', 'Male',0)
Insert into Students values ('Sara', 'vilium', 'Female',1)
Insert into Students values ('Mark', 'hash', 'Female',1)
Insert into Students values ('ABC', 'EFG', 'Male',0)


Step(2)  Now Go to your application and add a “Ado.NetDataModal “ then select Modal Fiirst approach then Give the connection and select your table from database. After click on OK your entity will show with “IsDiscard” column.

Step(3)  To Use Conditional Mapping
(A)                Right click on Entity and click  on Table Mapping a table a screen will come there you give the condition When IsDiscard = False


(B)                At this time if we try to build this solution it gives compilation error because it cannot map a column more then once.
(C)                For solving this problem we have to delete “IsDiscard” column from entity ,Because we have used this column on Conditional mapping


Add a Web form to the project and dragdown a gidview after that bind this gridview. For binding this gridview write this below code.
protected void Page_Load(object senderEventArgs e)
{
    StudentDBContext _student = new StudentDBContext();
    GridView1.DataSource = _student.Students;
    GridView1.DataBind();
}









No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...