Wednesday, August 25, 2010

Entity Framework 4

Entity Framewok 4 is a Object Relation Mapping Tool chain from Microsoft.
In fact it is much more than an ORM tool. It is going to be the future of Microsoft Data Access Technology. With Entity Framework in place programmers need not worry about database, tables, relations, Stored Procedure Name parameters and the like. Instead you work with a conceptual model that reflects your business objects just like working with objects in memory.Pro Entity Framework 4.0

Windows Forms Data Binding

Asp .Net and SaveChanges Method


WPF

Stored Procedure in Entity Framework

Asp .Net Dynamic Data


Contact Management System Table Structure
To make things simple I am using just two tables Contact Groups and Contacts.


create table ContactGroups(GroupId int identity(1,1) primary key,
GroupName varchar(40))

create table Contacts (ContactId int primary key identity(1,1) ,
GroupId int references ContactGroups(GroupId), ContactName varchar(40),
Phone varchar(15), Email varchar(40))



Entity Data Model(EDM)
Entity Data Model is the bridge between the database and the conceptual model.
The EDM is represented by a single XML document at design time which will be split into three sections at run time representing Conceptual (CSDL - Conceptual Schema Definition Language), Storage (SSDL - Storage Schema Definition Language) and Mapping Layers (MDL- Mapping Definition Language).

First lets see how to create an Entity Data Model.
Entity Framework 4 requires .Net 4. I am starting an Empty Asp .Net Project.




















In the Add New Item Dialog I am selecting ADO .NET Entity Data Model.





















The screen asks us whether to start by Generating from Database or start with an empty model.
Lets start with Generating from Database.

Entity Framework also support Domain Driven development that well will take up on another blog.



In the Choose your Data Connection Screen you can select the database to work with. I am select ContactManagement database a simple database with just two table.
At the bottom of the wizard is the Entity Container Class which follows a naming pattern like Entities. So in our case it is ContactMangementEntities.




















The next screen list all the database object. I am selecting just one table to make things simple.

Bottom of the screen are two new features. Select both the options.



















Now you are receiving the designer. Individual items in an EDM are called Entities. In our example there is only one entity.

Add a GridView on the the form. From the Smart Tag of GridView select New Data Source from Choose Data Source option.
From the Choose Data Source Type select Entity. Click Next. From the Named Connection select ContactManagementEntities. Click Next. Select ContactGroup from EntitySetName. Since we have added only one Entity you will see just ContactGroup in the combo box. Click finish and you can see the GridView filled with data.


Windows Forms Data Binding
In the previous example we saw working with wizards. In this section we are going to make our hands dirty by writing some code. As in the previous example here too I am creating a Entity Data Model.






































Now go to Data Menu and select Show Data Sources which will show the Data Sources window. Click on the first icon in the Data Sources window, ie. the Add New Data Source icon. This will invoke Data Source Configuration Wizard. Select Object and proceed with the wizard.
This wizard will create an Object Data Source.
Drag the ContactGroup on to the form. Visual Studio will create the form for you with button for CRUD operations.

Add the following following code to the load event of the form.


private void Form1_Load(object sender, EventArgs e)
{
ContactManagementEntities con = new ContactManagementEntities();Programming Entity Framework: Building Data Centric Apps with the ADO.NET Entity Framework
var Grps = from p in con.ContactGroups
select p;
contactGroupBindingSource.DataSource = Grps;
}



















Windows Forms ComboBox Grid Lookup


ContactManagementEntities cont = new ContactManagementEntities();
List<ContactGroup> Grps;
List<Contact> Contacts;

bool flag = false;
private void ComboOneToMany_Load(object sender, EventArgs e)
{
Grps = cont.ContactGroups.ToList();

Contacts = cont.Contacts.ToList();


FillCombos();
flag = true;
}

private void FillCombos()
{

cboGroups.DisplayMember = "GroupName";
cboGroups.DataSource = Grps;
cboGroups.ValueMember = "GroupId";
}

private void cboGroups_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag == true)
{
MessageBox.Show(cboGroups.SelectedValue.ToString());
int intGroupId = Int32.Parse(cboGroups.SelectedValue.ToString());
var Conts = from p in cont.Contacts
where p.GroupId == intGroupId
select new { p.ContactName };
dataGridView1.DataSource = Conts;
}



















Joins
int intGroupId = Int32.Parse(cboGroups.SelectedValue.ToString());
var Contacts = from p in con.ContactGroups
join c in con.Contacts on p.GroupId equals c.GroupId
where p.GroupId == intGroupId
orderby p.GroupName;
dataGridView1.DataSource = Conts;



Asp .net


ContactManagementModel.ContactManagementEntities con;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnAdd_Click(object sender, EventArgs e)
{
con = new ContactManagementModel.ContactManagementEntities();
var Grp = new ContactManagementModel.ContactGroup { GroupName = txtGroup.Text };
con.AddToContactGroups(Grp);
con.SaveChanges();
txtGroup.Text = "";
txtGroup.Focus();
Response.Write("Record Saved");
}



Top












Delete Record using DeleteObject Method

ContactManagementModel.ContactManagementEntities context = new ContactManagementModel.ContactManagementEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlGroups.DataSource = context.ContactGroups;
ddlGroups.DataTextField = "GroupName";
ddlGroups.DataValueField = "GroupId";
DataBind();
ddlGroups.Items.Add("");
ddlGroups.SelectedValue = "";
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{


}
protected void btnDelete_Click(object sender, EventArgs e)
{
int intGroupId = Int32.Parse(ddlGroups.SelectedValue.ToString());
var Grp = context.ContactGroups.Where(p => p.GroupId == intGroupId).First();
context.DeleteObject(Grp);
context.SaveChanges();
Response.Write("Record Deleted");
}

Updating Records
private void btnUpdate_Click(object sender, EventArgs e)
{
int intGroupId = Int32.Parse(cboGroup.SelectedValue.ToString());

var Grp =
context.ContactGroups.Where(p => p.GroupId == intGroupId).First();

Grp.GroupName = txtGroupName.Text;
context.SaveChanges();
MessageBox.Show("Record Updated");
}

WPF
 <Grid>
<TabControl Height="279" HorizontalAlignment="Left" Margin="20,20,0,0" Name="tabControl1" VerticalAlignment="Top" Width="471">
<TabItem Header="Groups" Name="tabItem1">
<Grid>
<TabControl Height="172" HorizontalAlignment="Left" Margin="25,19,0,0" Name="tabControl2" VerticalAlignment="Top" Width="350">
<TabItem Header="Insert" Name="tabItem2">
<Grid />
</TabItem>
<TabItem Header="Show">
<Grid>
<DataGrid AutoGenerateColumns="True" Height="100" HorizontalAlignment="Left" Margin="18,20,0,0" Name="dgdGroups" VerticalAlignment="Top" Width="246" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</TabItem>
<TabItem Header="Contacts">
<Grid>
<TabControl Height="205" HorizontalAlignment="Left" Margin="28,22,0,0" Name="tabControl3" VerticalAlignment="Top" Width="341">
<TabItem Header="Insert" Name="tabItem3">
<Grid />
</TabItem>
<TabItem Header="Lookup">
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="114,21,0,0" Name="cboGroup" VerticalAlignment="Top" Width="120" />
<DataGrid AutoGenerateColumns="True" Height="113" HorizontalAlignment="Left" Margin="41,50,0,0" Name="dgdContacts" VerticalAlignment="Top" Width="237" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</TabItem>
</TabControl>
</Grid>


  ContactManagementEntities context = new ContactManagementEntities();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var Grp = from p in context.ContactGroups
select new { p.GroupId, p.GroupName };
dgdGroups.ItemsSource = Grp;
cboGroup.ItemsSource = Grp;
cboGroup.DisplayMemberPath = "GroupName";
cboGroup.SelectedValuePath = "GroupId";
}

private void cboGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

int intGrp = Int32.Parse(cboGroup.SelectedValue.ToString());

var Contacts = from p in context.Contacts
where p.GroupId == intGrp
select new { p.ContactName, p.Email };

dgdContacts.ItemsSource = Contacts;
}

Max

ContactManagementEntities context = new ContactManagementEntities();
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
  try
  {
      var intGroupId = (from p in context.ContactGroups
                                  select p.GroupId).Max();

      intGroupId++;

      var Grp = new ContactGroup { GroupId = intGroupId, GroupName = txtGroupName.Text };
     context.AddToContactGroups(Grp);

    context.SaveChanges();
    MessageBox.Show("Record Saved");
  }
  catch (Exception ex)
  {
       MessageBox.Show(ex.ToString());
  }
     
 }

Related Blog

Entity Framework Model First

Entity Framework and Stored Procedures

 

No comments:

Post a Comment