调用并插入存储过程API核心2.1 [英] Call and insert stored procedure API core 2.1

查看:88
本文介绍了调用并插入存储过程API核心2.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 

1- code 存储过程

1- code stored procedure

ALTER PROCEDURE [dbo].[SP_InsertFollow]
	
(
	@School_Id int,
    @Employee int ,
	@No_teachers int ,
	@No_Ma int ,
	@No_us int
AS
BEGIN 

INSERT INTO Follow_Basic
                         ( School_Id, Employee_Id, No_teachers, No_Ma, No_us)
VALUES        (@School_Id,@Employee,@No_teachers,@No_Ma,@No_us)

 END

班级名称  SP_InsertFollow

Class Name SP_InsertFollow

    public class SP_InsertFollow
    {
        public int School_Id { get; set; }
        [Key]
        public int Employee { get; set; }
        public int No_teachers { get; set; }
        public int No_Ma { get; set; }
        public int No_us { get; set; }
    }

3- Class  DbContext

3- Class DbContext

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiOfficeEdu.Models
{
    public class MyTestDBContext : DbContext
    {

        public  MyTestDBContext(DbContextOptions<MyTestDBContext> options)
         : base(options)
        { }
       
        public virtual DbSet<SP_InsertFollow> SP_InsertFollow { get; set; }
    }

}
    

控制器类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApiOfficeEdu.Models;

namespace WebApiOfficeEdu.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InsertDataController : ControllerBase
    {
        private readonly MyTestDBContext _context;

        public InsertDataController(MyTestDBContext context)
        {
            _context = context;
        }

        [HttpPost]
        public void PostSP_InsertFollow()
        {
        _context.Query<SP_InsertFollow>().AsNoTracking().FromSql("SP_InsertFollow @School_Id," +
                        "@Employee,@No_teachers,@No_Ma,@No_us", 1001, 100, 500, 200, 100);

        }
    }
}

如果运行错误

System.InvalidOperationException:'无法为'SP_InsertFollow'创建DbQuery,因为它不是查询类型。使用DbContext.Set方法代替创建一个DbSet。'
$

请帮助我Sq Linq API

推荐答案

您好,

请参阅以下Microsoft
文档
,了解如何将SP与EF一起使用,并在
此页面
,显示SP使用与第一个链接相同的语法执行INSERT。

See the following Microsoft documentation for how to use a SP with EF and at the bottom of this page which shows an SP performing a INSERT using the same syntax as in the first link.

CREATE PROCEDURE usp_InsertCategory
 @CategoryName Varchar(300)
AS
BEGIN
    SET NOCOUNT ON;
    Insert into Categories Values (@CategoryName)
END
GO

以上代码。

var catName = "Personal Care";
dataContext.Database
           .ExecuteSqlCommand("usp_InsertCategory @p0", catName);


这篇关于调用并插入存储过程API核心2.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆