Entity Framework Fluent API Stored Procedure Calling (DataBase First) Example

Create database table:
CREATE TABLE [dbo].[Product]
(  
 [ProductId] [int] IDENTITY(1,1) NOT NULL,
 [ProductName] [varchar](50) NULL,
 [ProductDescription] [varchar](1000) NULL,
 [ProductPrice] numeric(5,2) NULL
) ON [PRIMARY]
GO

Insert sample data:
Insert into Product ([ProductName] ,[ProductDescription],[ProductPrice]) 
Values ('Product-1','sample product description-1',631.81)

Insert into Product ([ProductName] ,[ProductDescription],[ProductPrice]) 
Values ('Product-2','sample product description-2',863.28)

Insert into Product ([ProductName] ,[ProductDescription],[ProductPrice]) 
Values ('Product-3','sample product description-3',640.01)

Insert into Product ([ProductName] ,[ProductDescription],[ProductPrice]) 
Values ('Product-4','sample product description-4',542.21)

Insert into Product ([ProductName] ,[ProductDescription],[ProductPrice]) 
Values ('Product-5','sample product description-5',178.54)

Create simple Stored Procedure to get product list:
CREATE PROCEDURE [dbo].[GetProductsList]
AS
BEGIN
 SET NOCOUNT ON;
 SELECT ProductId,ProductName Name,
  ProductDescription [Description],ProductPrice Price 
 FROM product
END

Product Model:
public partial class Product
    {
        public Product()
        {
            
        }

        public int ProductID { get; set; }

        [Required(ErrorMessage = "Required")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Display(Name = "Description")]
        public string Description { get; set; }

        [Required(ErrorMessage = "Required")]
        [Display(Name = "Price")]
        public decimal Price { get; set; }
    }
public class ProductConfiguration : EntityTypeConfiguration
 {
     public ProductConfiguration()
     {
          this.HasKey(b => b.ProductID);
          this.ToTable("Product");
          this.Property(b => b.ProductID).HasColumnName("ProductId");
          this.Property(b => b.Name).HasColumnName("ProductName");
          this.Property(b => b.Description).HasColumnName("ProductDescription");
          this.Property(b => b.Price).HasColumnName("ProductPrice");
     }
 }

Controller:
public ViewResult Index()
  {
       var myEntity = db.Prodcuts.SqlQuery("dbo.GetProductsList");
       return View(myEntity.ToList());
  }


Click here to download sample code with Database scripts


Entity Framework Fluent API Stored Procedure Calling (DataBase First) Example Entity Framework Fluent API Stored Procedure Calling (DataBase First) Example Reviewed by Mara on 5:51 AM Rating: 5

No comments:

Powered by Blogger.