How to call Stored Procedure in Entity Framework 6 (Code-First)?

前端 未结 21 2458
滥情空心
滥情空心 2020-11-22 05:04

I am very new to Entity Framework 6 and I want to implement stored procedures in my project. I have a stored procedure as follows:

ALTER PROCEDURE [dbo].[ins         


        
21条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:04

    Using your example, here are two ways to accomplish this:

    1 - Use Stored procedure mapping

    Note that this code will work with or without mapping. If you turn off mapping on the entity, EF will generate an insert + select statement.

    protected void btnSave_Click(object sender, EventArgs e)
    {
         using (var db = DepartmentContext() )
         {
            var department = new Department();
    
            department.Name = txtDepartment.text.trim();
    
            db.Departments.add(department);
            db.SaveChanges();
    
            // EF will populate department.DepartmentId
            int departmentID = department.DepartmentId;
         }
    }
    

    2 - Call the stored procedure directly

    protected void btnSave_Click(object sender, EventArgs e)
    {
         using (var db = DepartmentContext() )
         {
            var name = new SqlParameter("@name", txtDepartment.text.trim());
    
            //to get this to work, you will need to change your select inside dbo.insert_department to include name in the resultset
            var department = db.Database.SqlQuery("dbo.insert_department @name", name).SingleOrDefault();
    
           //alternately, you can invoke SqlQuery on the DbSet itself:
           //var department = db.Departments.SqlQuery("dbo.insert_department @name", name).SingleOrDefault();
    
            int departmentID = department.DepartmentId;
         }
    }
    

    I recommend using the first approach, as you can work with the department object directly and not have to create a bunch of SqlParameter objects.

提交回复
热议问题