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

前端 未结 21 2047
滥情空心
滥情空心 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:10

    You can call a stored procedure in your DbContext class as follows.

    this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);
    

    But if your stored procedure returns multiple result sets as your sample code, then you can see this helpful article on MSDN

    Stored Procedures with Multiple Result Sets

    0 讨论(0)
  • 2020-11-22 06:10

    I solved it with ExecuteSqlCommand

    Put your own method like mine in DbContext as your own instances:

    public void addmessage(<yourEntity> _msg)
    {
        var date = new SqlParameter("@date", _msg.MDate);
        var subject = new SqlParameter("@subject", _msg.MSubject);
        var body = new SqlParameter("@body", _msg.MBody);
        var fid = new SqlParameter("@fid", _msg.FID);
        this.Database.ExecuteSqlCommand("exec messageinsert @Date , @Subject , @Body , @Fid", date,subject,body,fid);
    }
    

    so you can have a method in your code-behind like this :

    [WebMethod] //this method is static and i use web method because i call this method from client side
    public static void AddMessage(string Date, string Subject, string Body, string Follower, string Department)
    {
        try
        {
            using (DBContext reposit = new DBContext())
            {
                msge <yourEntity> Newmsg = new msge();
                Newmsg.MDate = Date;
                Newmsg.MSubject = Subject.Trim();
                Newmsg.MBody = Body.Trim();
                Newmsg.FID= 5;
                reposit.addmessage(Newmsg);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
    

    this is my SP :

    Create PROCEDURE dbo.MessageInsert
    
        @Date nchar["size"],
        @Subject nchar["size"],
        @Body nchar["size"],
        @Fid int
    AS
        insert into Msg (MDate,MSubject,MBody,FID) values (@Date,@Subject,@Body,@Fid)
        RETURN
    

    hope helped you

    0 讨论(0)
  • 2020-11-22 06:10
    object[] xparams = {
                new SqlParameter("@ParametterWithNummvalue", DBNull.Value),
                new SqlParameter("@In_Parameter", "Value"),
                new SqlParameter("@Out_Parameter", SqlDbType.Int) {Direction = ParameterDirection.Output}};
    
            YourDbContext.Database.ExecuteSqlCommand("exec StoreProcedure_Name @ParametterWithNummvalue, @In_Parameter, @Out_Parameter", xparams);
            var ReturnValue = ((SqlParameter)params[2]).Value;  
    
    0 讨论(0)
提交回复
热议问题