I Explained before that 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.
Here we will learn Conditional mapping in Entity Framework with code first Approach.
Step 1: Create a new web application And install Entity
framework..
Step 2: Add a class to the project. Give the Name as Student.cs. Write Below code.
Step 2: Add a class to the project. Give the Name as Student.cs. Write Below code.
namespace EFTableSplitting
{
public class Student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public bool IsDiscard
s{ get; set; }
}
}
|
Step 3: Add a class to the project For the DBContext and give the name it asStudentDBContext.cs. And Write below code.
using System.Data.Entity;
namespace EFTableSplitting
{
public class StudentDBContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder _Modal)
{
_Modal.Entity<Student>()
.Map(c => c.Requires("IsDiscard")
.HasValue(false))
.Ignore(c => c.IsDiscard);
base.OnModelCreating(_Modal);
}
}
}
|
Step 4: Add the database
connection string in web.config file.
<connectionStrings>
<add name="StudentDBContext"
connectionString="server=.; database=entitysplitting; integrated security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
|
Step 5: Add a webform to the project. Go to Tool Box and Drag and drop a GridView control.
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
s
|
Step 6: Write below code at page load event.
protected void Page_Load(object sender, EventArgs e)
{
StudentDBContext studentDBContext = new StudentsDBContext();
GridView1.DataSource = studentDBContext.Students.ToList();
GridView1.DataBind();
}
|
Step 7: If you already have entitysplitting database in SQL Server. Delete it first
And then Run the application.
Step 8: At this point, run the application. entitysplitting database and Student table should be created by the entity framework.
Step 9: Insert data using the following SQL script
Insert into Students values ('Munesh', 'Sharma',
Male',m@g.com,5555555555)
Insert into Students values ('Rahul', 'Sharma',
'Male',R@g.com,333333333)
Insert into Students values ('Sara', 'vilium',
'Female',S@g.com,111111111)
Insert into Students values ('Mark', 'hash',
'Female',M1@g.com,2222222222)
Insert into Students values ('ABC', 'EFG',
'Male',A@g.com,6666666666)
|