Showing posts with label Entity Framework 4. Show all posts
Showing posts with label Entity Framework 4. Show all posts

Saturday, February 19, 2011

Razor View Engine and Visual Studio

The inspiration for this blog on Razor was the Web Camp conducted by Microsoft Evangelists Nahas Mohammed  and Ramaprasanna Chellamuthu on February 18 at Kochi. We received great insight into Razor View Engine and Web Matrix.
A few of the audience were invited to the stage and it was more of an interactive Code camp.


I am using Visual Web Developer 2010, a free tool from Microsoft for developing Asp .Net Applications. All the examples will work in Visual Studio.  I have already installed Asp .Net MVC 3 in my machine.

Visual Studio 2010 / Visual Web Developer 2010 comes will Intellisense and debugging support for Razor. Unlike Asp .Net Web Forms in Razor the Visual Interface is defined using HTML.

I am starting an Empty Web Site and Adding an Empty Razor Page.







@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello welcome to Razor"
    }
    
}
<form method=post>
<p>
@strName
</p>
<input id="Submit1" type="submit" value="submit" />
</form>






Inside a block each statement should end with a semicolon. Inside html you can call the memory variable using @ symbol. There semicolon should not be present.

We are checking a form post using IsPost. On Clicking the Submit buttom a Form POST will occur after that the memory variable will be assigned the Hello message and that message will be dispayed.



Using can use Html Tab in the Toolbox to add Html tags to the form.


You can see that the auto completion feature is available.

@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello " + Request["txtName"];
    }
 }
<form method=post>
<p>
@strName
</p>
Name 
<input Name="txtName" type="text" />
<br />
<input id="Submit1" type="submit" value="submit" />
</form>



In the above example we extracting the value of textbox using Request.








@{
    var sum = 0;
    if(IsPost)
    {
        sum = Request["txtValue1"].AsInt() + Request["txtValue2"].AsInt();
           
    }
    
}

<form method =post>
<p>
@sum
</p>
Value 1<input Name = "txtValue1" type="text" />
</br>
Value 2<input Name = "txtValue2" type="text" />
</br>
<input id="Submit1" type="submit" value="submit" />
</form>

AsInt() is used to convert the value to Integer.



Session
//Session.cshtml
@{
    Session["Name"] =  "Shalvin"; 
}

<form method =post>
<a href = "@Href("Welcome")">Welcome</a>
</form>





//Welcome.cshtml
@{
var strName = "Hello " + Session["Name"];
}




@strName





Href method is used to create paths to resources like Web pages.
In the first page we are defining the session variable and in the second page we extracting the value of Session variable.


Entity Framework
I am creating an Entity Data Model is shown in the figure



@{
    var context = new ContactManagementModel.ContactManagementEntities();

    var Grps = context.ContactGroups;

    var gd = new WebGrid(Grps);
}

<html>
<body>
 @gd.GetHtml();
</body>
</html>






WebGrid helper can be used to display day is a tabular manner.





@{
    var context = new ContactManagementModel.ContactManagementEntities();
  var strMessage = "";
    if(IsPost)
    {
    var Grp = new ContactManagementModel.ContactGroup{GroupName = Request["txtGroupName"]};

    context.AddToContactGroups(Grp);
    context.SaveChanges();
    strMessage = "Record Saved";
    }
        
}

<form method = "post">
<p>
@strMessage
</p>
Group Name 
<input Name = "txtGroupName" type="text" />
</br>
    <input id="Submit1" type="submit" value="submit" />
</form>

Saturday, January 15, 2011

Asp .Net Mvc with Entity Framework










































































public ActionResult Index()
{
var Grp = context.ContactGroups;
return View(Grp);
}







//
// GET: /Home/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Home/Create

[HttpPost]
public ActionResult Create(ContactGroup Grp)
{
if (ModelState.IsValid)
{
try
{
context.AddToContactGroups(Grp);
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(Grp);
}
}
else
{
return View(Grp);
}
}





//
// GET: /Home/Edit/5

public ActionResult Edit(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
UpdateModel(Grp, collection.ToValueProvider());
context.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}






//
// GET: /Home/Delete/5

public ActionResult Delete(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
context.DeleteObject(Grp);
context.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}

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