Friday, August 27, 2010
Thursday, August 26, 2010
ADO.NET Entity (EDMX) : Insert Update and Delete with Relationship
Here I will use a database created by me. There will be two tables connected with each other. 
Now I will create TestDB.edmx out of this database.
Insert
using (TestDBEntities ctx = new TestDBEntities())
{
    //Create new Department
    Dept d = new Dept() { DeptName = "ADO Entity" };
    //Create new Employee 1
    EmpDept ed1 = new EmpDept() { EmpName = "ADO Employee 1" };
    //Create new Employee 2
    EmpDept ed2 = new EmpDept() { EmpName = "ADO Employee 2" };
    //Add employee to the Dept *OBJECT*
    d.EmpDept.Add(ed1);
    d.EmpDept.Add(ed2);
    //Updating the context
    ctx.AddToDept(d);
    //Save to Database
    ctx.SaveChanges();
}
Update
using (TestDBEntities ctx = new TestDBEntities())
{
    //Get an existing Department
    Dept dep = (from d in ctx.Dept
                where d.DeptId == 22
                select d).First();
    //Set new Department name
    dep.DeptName = "ADO.NET 3.0";
    //Create new Employee 2
    EmpDept ed2 = new EmpDept() { EmpName = "ADO 2" };
    //Add *new* employee to the Dept *OBJECT*
    dep.EmpDept.Add(ed2);
    //Save to Database
    ctx.SaveChanges();
}
Delete
using (TestDBEntities ctx = new TestDBEntities())
{
    //Get an existing Department
    Dept dep = (from d in ctx.Dept.Include("EmpDept")
                where d.DeptId == 22
                select d).First();
    /*
     Needd to do ToList() becuase once you delete
     a record then iteration will not be possible.          
    */ 
    foreach (EmpDept ed in dep.EmpDept.ToList())
    {
        //This removes relationship from Context
        dep.EmpDept.Remove(ed);
        //Delete it from context
        ctx.DeleteObject(ed);        
    }
    //Delete the master table
    ctx.DeleteObject(dep);
        
    //Save to Database
    ctx.SaveChanges();
Saturday, August 21, 2010
Using ImageUrl in sitemap for menu
The imageUrl property shown here is a custom attribute and gets added to the attributes of the SiteMapNode, which can be accessed within the MenuItemDataBound event; this is called for every menu item as it's bound to the underlying siteMapData. So you could have this:
protected void menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
    SiteMapNode node = e.Item.DataItem as SiteMapNode;
    if (!string.IsNullOrEmpty(node["imageUrl"]))
        e.Item.ImageUrl = node["imageUrl"];
}  
To access the attributes you just index into the default collection on the SiteMapNode.
the advantage of this approach is twofold; you don't pollute your title with HTML hacks, and you keep the image data as a separate item, alongside the other site map data.
