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

Friday, June 29, 2012

Kendo UI :Web development framework- Part 2

The MVVM model is most popular now a days . Here we will see with the sample example the use of MVVM in MVC.

To start with  MVVM  we need to first create a View Model, A view model is an observable object. This object has properties and methods. Each property will be bound to something in the HTML. In MVVM, this binding is two way, meaning that if the binding changes on the UI, the model changes, and vice versa.

Let us take a sample example where we will take display a grid and a drop down box, firstly i will create a HTML controls for grid and drop-down. And grid will be using a Template column.

 <script id="rowTemplate" type="text/x-kendo-tmpl">  
   <tr>  
     <td>${ UserName }</td>  
     <td>${ GroupName }</td>  
     <td>  
      <input type="image" id="btnremove" src="/Content/Images/DeleteIcon.gif" data-bind='events { click : removeUser }, enabled: btnSaveIsEnabled' style="width:20px;height:20px;"/></td>  
   </tr>  
 </script>  
 <div id="UserTab">  
   <div id="userGrid" data-role="grid" data-bind="source: User.UsersOf"  
     data-row-template="rowTemplate" data-columns='["User", "Group", "Remove" ]' data-pageable='{"pageSize":10}'>  
   </div>  
   <table style="width: 100; margin-top: 20px; margin-bottom: 20px">  
     <tr>  
       <td style="width: 45%">  
         <select id="dduser" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableUsers, value: selectedUser, events: { change : userSelectChange }" />  
       </td>  
       <td style="width: 45%">  
         <select id="ddgroup" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableGroups, value: selectedGroup, events: { change : groupSelectChange }" />  
       </td>  
       <td style="width: 10%">  
         <button id="btnSave" class="k-button" style="width: 75px" data-bind='events { click : addUser }, text: addUserText, enabled: btnSaveIsEnabled'>  
         </button>  
       </td>  
     </tr>  
   </table>  
   <a href='@Url.Action("Create", "Group", new { })' style="color: Blue; text-decoration: true;">  
     Add New Group</a><br />  
   <a href='@Url.Action("Index", "Type", new { })' style="color: Blue; text-decoration: true;">  
     Add New Type</a>  
 </div>  

Here we have created a UserViewModel that is binded to the div id :UserTab, This example also shows how to add and delete user using MVVM pattern.

 <script language="javascript" type="text/javascript">  
   $(document).ready(function () {  
     var UserViewModel = kendo.observable({  
       UserSource: new kendo.data.DataSource({  
         transport: {  
           read: {  
             url: document.URL + "/GetUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) {  
               if (UserViewModel.UserSource == null) return;  
               UserViewModel.set("User", UserViewModel.UserSource.at(0));  
             },  
             data: { Id: 0, TypeId: 0 }  
           },  
           update: {  
             url: document.URL + "/AddUserToUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) { }  
           },  
           parameterMap: function (options, operation) {  
             if (operation !== "read" && options.models)  
               return { models: kendo.stringify(options.models) };  
             return options;  
           }  
         },  
         schema: {  
           model: { id: "Id" }  
         }  
       }),  
       User: null,  
       selectedGroup: null,  
       selectedUser: null,  
       Id: 0,  
       TypeId: 0,  
       btnSaveIsEnabled: false,  
       addUserText: 'Add',  
       groupSelectChange: function (e) { },  
       userSelectChange: function (e) { },  
       load: function (e) {  
         this.set("Id", e.Id);  
         this.set("TypeId", e.TypeId);  
         this.UserSource.read({ Id: e.Id, TypeId: e.TypeId });  
         $("#dduser").val("").data("kendoDropDownList").text("--Choose User--");  
         $("#ddgroup").val("").data("kendoDropDownList").text("--Choose Group--");  
       },  
       addUser: function (e) {  
         if (this.get("selectedUser") == null || this.get("selectedGroup") == null) {  
           alert("Please select User and Group");  
           return;  
         }  
         if (IsUserExist(this.get("selectedUser").Id, this.get("selectedGroup").Id)) {  
           alert("User already exist");  
           return;  
         }  
         var Id = this.get("Id");  
         var TypeId = this.get("TypeId");  
         $.post("/AddUserToUser", { Id: this.get("Id"), groupId: this.get("selectedGroup").Id, userId: this.get("selectedUser").Id },  
         function (data) {  
           if (data) {  
             UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
             aler("User/Group Added");  
           }  
           else  
             growlSad("User not Added");  
         });  
       },  
       removeUser: function (e) {  
         if (confirm("Are you sure you want to delete this user from group?")) {  
           var Id = this.get("Id");  
           var TypeId = this.get("TypeId");  
           $.post("/DeleteUser", { UserId: e.data.UserId },  
         function (data) {  
           UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
         });  
         }  
       }  
     });  
     kendo.bind($("#UserTab"), UserViewModel);  
     $(document).bind(Events.OnClicked, function (event, args) {  
       UserViewModel.load({ Id: args.Selected.Id, TypeId: args.Selected.TypeId });  
       UserViewModel.set("btnSaveIsEnabled", args.Selected.IsActive);  
     });  
     $(document).bind(window.Events.OnUpdated, function (e, args) {  
       ResetFormUser();  
     });  
     function IsUserExist(userId, groupId) {  
       var gridDataSource = UserViewModel.UserSource._data[0].UsersOf;  
       for (var i = 0; i < gridDataSource.length; i++) {  
         if (userId == gridDataSource[i].UserId && groupId == gridDataSource[i].GroupId)  
           return true;  
       }  
       return false;  
     }  
     function ResetFormUser() {  
       UserViewModel.load({ Id: 0, TypeId: 0 });  
       UserViewModel.set("btnSaveIsEnabled", false);  
     }  
   });  
 </script>  

Happy Coding :) 

Wednesday, June 20, 2012

Entity Framework 4 - Batch Updates

This article explains the batch update of data into data base using the Entityframework4.

Problem Statement:  We have a List of customer that needs to be updated in the data base.
I will directly jump on the code.

Here is the function which does the Batch update in a single database hit.

 public JsonResult Update(List<Customer> models)  
     {  
       using (var context = new NorthwindEntities())  
       {  
         //Attach each entity to a context entity  
         models.ForEach(a => context.Customers.Attach(a));  
         //Change all the object state to Modified  
          models.ForEach(s => context.ObjectStateManager.ChangeObjectState(s,   
                        EntityState.Modified));               
         //Save changes to the database    
         context.SaveChanges();  
       }  
        //Return the result  
       return Json(Details());  
     }  

 Note: Instead  EntityState.Modified you can use Added/Deleted/Detached

Happy Coding :)

Friday, June 8, 2012

Hierarchical-Data in Organization Structure View

While going through an interesting assignment i got to learn how to play with Hierarchical Database where the data in the data base are stored in the following format

Here the main challenge was to display the data in the following format


As we have may tree view structure available in the market, but they don't provide a org structure look & feel.

I took the reference of  http://dl.dropbox.com/u/4151695/html/jOrgChart/example/example.html and created a customized structure using which we can dynamically create organization structure.

Bellow is the location where i have kept the code and Database

Display-Hierarchical-Data Source Code
Database

When you build and run the code you need to provide the path as

http://localhost:[Port Number]/employeeTree/index

Happy Coding :)


Wednesday, May 23, 2012

EF Code First:Executing Stored Procedure

Code First in Entity Framework does not support Stored Procedure by default. We can not even map our Stored procedure to Entity. There are a many scenario we have seen where we are bound to use stored procedure for any database modifications (insert/update/delete). Here is how we can use stored procedure. 

Here i have created two Entities 


 public class Employee  
   {  
     public int Id { get; set; }  
     public string Name { get; set; }  
   }  
   public class Address:Employee  
   {  
     public string Address1 { get; set; }  
     public string Address2 { get; set; }  
     public string City { get; set; }  
     public int Pin { get; set; }  
   }  
-------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Now we create EmployeeDBContext 




 public class EmployeeContext : DbContext  
   {  
     public DbSet<Employee> EmployeeSet { get; set; }  
     public DbSet<Address> Address { get; set; }  
     public void AddEmp(Address Emp)  
     {  
       this.Database.ExecuteSqlCommand("exec AddEmpData @Name,@Address1,@Address2,@City,@pin,@Discriminator",  
               new SqlParameter("@Name", Emp.Name),  
               new SqlParameter("@Address1",Emp.Address1),  
               new SqlParameter("@Address2", Emp.Address2),  
               new SqlParameter("@City", Emp.City),  
               new SqlParameter("@Pin", Emp.Pin),  
               new SqlParameter("@Discriminator", "Address"));  
     }  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
       modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
     }  
   }  

--------------------------------------------------------------------------------------------------------------------------------------------------------------------
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Data.Entity;  
 namespace Calling_SP  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       var Address = new Address  
       {  
         Name="Nirbhay",  
         Address1 = "Wakad-1",  
         Address2 = "Silver Society",  
         City = "pune",  
         Pin = 411010  
       };  
       //Save Data to database        
       using (var context = new EmployeeContext())  
       {  
         context.AddEmp(Address);  
       }  
       Console.Write("Person saved !");  
       Console.ReadLine();  
        //Retrieving data from Database  
       using (var context = new EmployeeContext())  
       {  
         var result = context.Address.SqlQuery("GetEmpData").ToList<Address>();  
         foreach (var item in result)  
         {  
           Console.Write(item.Id);  
           Console.Write(item.Name);  
           Console.Write(item.Address1);  
           Console.Write(item.Address2);  
           Console.Write(item.City);  
           Console.Write(item.Pin);  
           Console.WriteLine();  
         }  
       }  
       Console.ReadLine();  
     }  
   }  
 }  
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
In App.Config set the desired connection string
 <?xml version="1.0" encoding="utf-8" ?>  
 <configuration>  
  <connectionStrings>  
   <add name="EmployeeContext" connectionString="data source=SY113;initial catalog=Employee;integrated security=True;" providerName="System.Data.SqlClient"/>  
  </connectionStrings>  
 </configuration>  
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Stored Procedure
 USE [Employee]  
 GO  
 /****** Object: StoredProcedure [dbo].[AddEmpData]  Script Date: 05/23/2012 12:27:49 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 CREATE procedure [dbo].[AddEmpData]  
 @Name nvarchar(max),  
 @Address1 nvarchar(max),  
 @Address2 nvarchar(max),  
 @City nvarchar(max),  
 @Pin int,  
 @Discriminator nvarchar(128)  
 AS  
 Begin  
 insert into Employee (Name,Address1,Address2,City,Pin,Discriminator)  
 values  
 (@Name,@Address1,@Address2,@City,@Pin,@Discriminator)  
 End  
 GO  
 *********************************************************************************************  
 USE [Employee]  
 GO  
 /****** Object: StoredProcedure [dbo].[GetEmpData]  Script Date: 05/23/2012 12:28:34 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 Create procedure [dbo].[GetEmpData]  
 AS  
 Begin  
 select * from Employee  
 End  
 GO  

---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Following are the 2 tables Created By EF.


You can see in the above DB Diagram there is a field Called Discriminator, it is Created by EF because we have inherited Employee Class in Address and the value for this field is Address.




Tuesday, May 8, 2012

Entity Framework Model First Approach using MVC3

If you don't yet have a database, you can begin by creating a model using the Entity Framework designer in Visual Studio. When the model is finished, the designer can generate DDL (data definition language) statements to create the database. This approach also uses an .edmx file to store model and mapping information. The What's New in the Entity Framework 4 tutorial includes a brief example of Model First development.

 Create Models:   
 --------------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Student  
   {  
     public int StudentID { get; set; }  
     public string LastName { get; set; }  
     public string FirstMidName { get; set; }  
     public DateTime EnrollmentDate { get; set; }  
     public virtual ICollection<Enrollment> Enrollments { get; set; }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Enrollment  
   {  
     public int EnrollmentID { get; set; }  
     public int CourseID { get; set; }  
     public int StudentID { get; set; }  
     public decimal? Grade { get; set; }  
     public virtual Course Course { get; set; }  
     public virtual Student Student { get; set; }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Course  
   {  
     public int CourseID { get; set; }  
     public string Title { get; set; }  
     public int Credits { get; set; }  
     public virtual ICollection<Enrollment> Enrollments { get; set; }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 Create DAL Folder and in that Create 2 Following Files  
 --------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Data.Entity;  
 using MVCWeb.Models;  
 using System.Data.Entity.ModelConfiguration.Conventions;  
 namespace MVCWeb.DAL  
 {  
   public class SchoolContext:DbContext  
   {  
     public DbSet<Student> Students { get; set; }  
     public DbSet<Enrollment> Enrollments { get; set; }  
     public DbSet<Course> Courses { get; set; }  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
       modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
     }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Data.Entity;  
 using MVCWeb.Models;  
 namespace MVCWeb.DAL  
 {  
   public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>  
   {  
     protected override void Seed(SchoolContext context)  
     {  
       var students = new List<Student>  
       {  
         new Student { FirstMidName = "Carson",  LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },  
         new Student { FirstMidName = "Meredith", LastName = "Alonso",  EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Arturo",  LastName = "Anand",   EnrollmentDate = DateTime.Parse("2003-09-01") },  
         new Student { FirstMidName = "Gytis",  LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Yan",   LastName = "Li",    EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Peggy",  LastName = "Justice",  EnrollmentDate = DateTime.Parse("2001-09-01") },  
         new Student { FirstMidName = "Laura",  LastName = "Norman",  EnrollmentDate = DateTime.Parse("2003-09-01") },  
         new Student { FirstMidName = "Nino",   LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }  
       };  
       students.ForEach(s => context.Students.Add(s));  
       context.SaveChanges();  
       var courses = new List<Course>  
       {  
         new Course { Title = "Chemistry",   Credits = 3, },  
         new Course { Title = "Microeconomics", Credits = 3, },  
         new Course { Title = "Macroeconomics", Credits = 3, },  
         new Course { Title = "Calculus",    Credits = 4, },  
         new Course { Title = "Trigonometry",  Credits = 4, },  
         new Course { Title = "Composition",  Credits = 3, },  
         new Course { Title = "Literature",   Credits = 4, }  
       };  
       courses.ForEach(s => context.Courses.Add(s));  
       context.SaveChanges();  
       var enrollments = new List<Enrollment>  
       {  
         new Enrollment { StudentID = 1, CourseID = 1, Grade = 1 },  
         new Enrollment { StudentID = 1, CourseID = 2, Grade = 3 },  
         new Enrollment { StudentID = 1, CourseID = 3, Grade = 1 },  
         new Enrollment { StudentID = 2, CourseID = 4, Grade = 2 },  
         new Enrollment { StudentID = 2, CourseID = 5, Grade = 4 },  
         new Enrollment { StudentID = 2, CourseID = 6, Grade = 4 },  
         new Enrollment { StudentID = 3, CourseID = 1      },  
         new Enrollment { StudentID = 4, CourseID = 1,      },  
         new Enrollment { StudentID = 4, CourseID = 2, Grade = 4 },  
         new Enrollment { StudentID = 5, CourseID = 3, Grade = 3 },  
         new Enrollment { StudentID = 6, CourseID = 4      },  
         new Enrollment { StudentID = 7, CourseID = 5, Grade = 2 },  
       };  
       enrollments.ForEach(s => context.Enrollments.Add(s));  
       context.SaveChanges();  
     }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 In Global.asax add the following on application Start  
 Database.SetInitializer<SchoolContext>(new SchoolInitializer());  
 -------------------------------------------------------------------------------------------------------------  
 Add Connection String in Web.config  
  <add name="SchoolContext" connectionString="data source=[ServerName];initial catalog=[DBName];integrated security=True;" providerName="System.Data.SqlClient"/>  
 -------------------------------------------------------------------------------------------------------------  
 Create a controller class, I have created the controller class for student  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using MVCWeb.DAL;  
 namespace MVCWeb.Controllers  
 {  
   public class StudentController : Controller  
   {  
     private SchoolContext db = new SchoolContext();  
     //  
     // GET: /Student/  
     public ActionResult Index()  
     {  
       return View(db.Students.ToList());  
     }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 Create the Index View for the same  
 @model IEnumerable<MVCWeb.Models.Student>  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 <p>  
   @Html.ActionLink("Create New", "Create")  
 </p>  
 <table>  
   <tr>  
     <th></th>  
     <th>  
       LastName  
     </th>  
     <th>  
       FirstMidName  
     </th>  
     <th>  
       EnrollmentDate  
     </th>  
   </tr>  
 @foreach (var item in Model) {  
   <tr>  
     <td>  
       @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |  
       @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |  
       @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })  
     </td>  
     <td>  
       @item.LastName  
     </td>  
     <td>  
       @item.FirstMidName  
     </td>  
     <td>  
       @String.Format("{0:g}", item.EnrollmentDate)  
     </td>  
   </tr>  
 }  
 </table>  



run the code and call Student/index it will create the database for you and add the data provided in the SchoolInitializer Class to respective tables.