Stored procedure use in EF
Stored procedures and user-defined functions (UDFs) in the database are represented as functions in entity framework. So EDM won’t have any entity or other stuff for stored procedures in the EDM designer.
USE [MyDB]
GO
/****** Object: StoredProcedure [dbo].[InsertRole] Script Date: 08/27/2014 11:10:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertRole]
(
@roleName varchar(100)
)
AS
BEGIN
INSERT INTO [Role]
([RoleName])
VALUES
(@roleName)
END
We would see in InsertRole stored procedure added in Function Imports with new complex type InsertRole_Result in Model Browser. Whenever we import stored procedure into model, it creates new complex type with the name {sp name}_Result by default.
Following example is that how to define insertrole sp in model namespace and entities class.
Function imports are based on stored procedures. To map a function import to a complex type, the columns returned by the corresponding stored procedure must match the properties of the complex type in number and must have storage types that are compatible with the property types.
DbContext —A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
When using the Code First approach, the System.Data.Entity.DbSet<TEntity>properties on the derived context are used to build a model by convention.
namespace TypeSettingWeb.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class MyEntities : DbContext
{
public MyEntities()
: base(“name=MyEntities”)
{
}
public virtual int InsertRole(string roleName)
{
var roleNameParameter = roleName != null ?
new ObjectParameter(“roleName”, roleName) :
new ObjectParameter(“roleName”, typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction(“InsertRole”, roleNameParameter);
}
}}
DbSet —A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.Set method.
Following is use for Datatable mapping to EF.it is using of Dbset properties.
public virtual DbSet<ActionPermission> ActionPermissions { get; set; }