Call stored procedure from Entity Framework 6.1.3 code-first

c# ef-code-first entity-framework entity-framework-6

Question

Please consider this code - I created a stored procedure:

CREATE PROCEDURE InsertRegion
    @RegionID int,
    @RegionDesc nvarchar(50)
AS
BEGIN
    INSERT INTO [dbo].[Region]
    VALUES (@RegionID, @RegionDesc)
END

and I want to call this procedure from my repository class:

 using (Model1 ent = new Models.Model1())
 {
     List<SqlParameter> parameters = new List<SqlParameter>();
     parameters.Add(new SqlParameter("RegionID", 100));
     parameters.Add(new SqlParameter("RegionDesc", "Nima"));

     ent.Database.SqlQuery<Region>("exec InsertRegion", parameters.ToArray());
  }

but nothing happens. I change the last line to:

ent.Database.SqlQuery<Region>("exec InsertRegion @RegionID, @RegionDesc ", parameters.ToArray());

but again, nothing happens.

Where is the problem?

Thanks

1
0
12/25/2016 9:52:35 PM

Accepted Answer

Use without exec :

using (Model1 ent = new Models.Model1())
{
    var regionID= new SqlParameter("@RegionID", 100);
    var regionDesc= new SqlParameter("@RegionDesc", "Nima");

    ent.Database.SqlQuery<Region>("InsertRegion @RegionID ,@RegionDesc", regionID ,regionDesc);
}

but in your sp not returning any recored so you can use this also :

using (Model1 ent = new Models.Model1())
{
    var regionID= new SqlParameter("@RegionID", 100);
    var regionDesc= new SqlParameter("@RegionDesc", "Nima");

    ent.Database.ExecuteSqlCommand("InsertRegion @RegionID ,@RegionDesc", regionID ,regionDesc);
}
1
12/25/2016 4:04:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow