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.




Friday, May 18, 2012

Using Model Metadata

When we are using Runtime Scaffolding to generate view, We are using @Html.EditorForModel() so here it will populate the model for editing but if we want some fields that should be non editable that we use the model meta data feature, The name space that we need to include is System.Web.Mvc .

Following are some of its attribute that we can use:
  • [HiddenInput] : If we don't want the property to be editable
  • [HiddenInput(DisplayValue=false)] :  If we don't want to display the value.
The Fields will be generated in the html but the value will be hidden.  If you are using [ScaffoldColumn(false)] the column will not be generated.

Bellow is the example that explains the usage.
-------------------------------------------------------------------------------------------------------------
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.ComponentModel.DataAnnotations;  
 using System.Web.Mvc;  
 namespace Using_Model_Metadata.Models  
 {  
   public class Product  
   {  
     [HiddenInput]  
     public int Id { get; set; }  
     public string Name { get; set; }  
     public string Category { get; set; }  
     public decimal Price { get; set; }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using Using_Model_Metadata.Models;  
 namespace Using_Model_Metadata.Controllers  
 {  
   public class ProductController : Controller  
   {  
     //  
     // GET: /Product/  
     public ActionResult Index()  
     {  
       return View(GetProduct());  
     }  
     public Product GetProduct()  
     {  
       Product product = new Product { Id = 1, Name = "Kayak", Category = "Watersports", Price = 275m };  
       return product;  
     }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 @model Using_Model_Metadata.Models.Product  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 @Html.EditorForModel()  
-------------------------------------------------------------------------------------------------------------
Output

Thursday, May 17, 2012

Rendering a Child Action

You can invoke a child action using the Html.Action helper. With this helper, the action method is
executed, the ViewResult is processed, and the output is injected into the response to the client.



Below is the example that explain how you can implement child Action
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 namespace child_Action.Controllers  
 {  
   public class ChildActionController : Controller  
   {  
     //  
     // GET: /ChildAction/  
     public ActionResult Index()  
     {  
       return View();  
     }  
     public ActionResult ChildActionDemo()  
     {  
       return View();  
     }  
     [ChildActionOnly]  
     public ActionResult Time()  
     {  
       return PartialView(DateTime.Now);  
     }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 View -> ChildAction->ChildActionDemo  
 @{  
 ViewBag.Title = "Child Action Demonstration";  
 }  
 <p>This is the method rendered by the action method</p>  
 @Html.Action("Time")  
 <p>This is the method rendered by the action method again</p>  
 --------------------------------------------------------------------------------------------------------------  
 Partial View: Shared->Time  
 @model DateTime  
 <p>The time is: @Model.ToShortTimeString()</p>