I'm using stored procedure, SQL Server, EF (code first). I have a stored procedure created in the database and I want to call it from my code.
Stored procedure:
CREATE PROCEDURE uspCreateLocal
-- Add the parameters for the stored procedure here
@Direccion varchar(100),
@Nombre varchar(80),
@Fijo varchar(9),
@Celular varchar(9),
@Administrador int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO Locales (Direccion, Nombre, Fijo, Celular, Administrador)
VALUES(@Direccion, @Nombre, @Fijo, @Celular, @Administrador)
SELECT SCOPE_IDENTITY() AS LocalId
END
GO
From my code I want to call it
public void InsertOrUpdate(Local entity)
{
using (var context = new PosContext())
{
if (entity.LocalId == default(int))
{
bool exist = Exist(o => o.Nombre == entity.Nombre);
if(exist)
throw new ArgumentException("El Local, que intenta registrar ya existe.");
else
{
context.Locales.Add(entity);
context.SaveChanges();
}
}
else
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
}
}
I'm going to replace the Add part with the store. How should I call him and send him the parameters?
I'm doing it this way:
public void InsertOrUpdate(Local entity)
{
using (var context = new PosContext())
{
if (entity.LocalId == default(int))
{
bool exist = Exist(o => o.Nombre == entity.Nombre);
if(exist)
throw new ArgumentException("El Local, que intenta registrar ya existe.");
else
{
//context.Locales.Add(entity);
//context.SaveChanges();
DbModelBuilder modelBuilder = new DbModelBuilder();
modelBuilder.Entity<Local>()
.MapToStoredProcedures(s =>
s.Insert(i => i.HasName("uspCreateLocal")
.Parameter(b => b.Direccion, "Direccion")
.Parameter(b => b.Nombre, "Nombre")
.Parameter(b => b.Fijo, "Fijo")
.Parameter(b => b.Celular, "Celular")
.Parameter(b => b.Administrador, "Administrador")));
context.SaveChanges();
}
}
else
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
}
I can not save the new record in the db because it is out of context. How can I solve it?