在ASP.Net Core中实现ADO连接

sta*_*ons 5 c#

我需要从 .Net Core 项目中的数据库获取存储过程。通常我通过这样做来运行这个存储过程:

首选代码

readonly private SqlConnection _dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString);

public int Insert(Employee employee)
{
    var result = 0;
    using (var cmd = new SqlCommand("Sp_Insert", _dbConnection) { CommandType = CommandType.StoredProcedure })
    {
        try
        {
            cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
            cmd.Parameters.AddWithValue("@LastName", employee.LastName);
            cmd.Parameters.AddWithValue("@EmployeeCode", employee.EmployeeCode);
            cmd.Parameters.AddWithValue("@Position", employee.Position);
            cmd.Parameters.AddWithValue("@Office", employee.Office);

            _dbConnection.Open();
            result = cmd.ExecuteNonQuery();
        }
        catch
        {
            // ignore
        }
        finally
        {
            _dbConnection.Close();
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

我的连接字符串位于 Web.config 中,但对于 .net Core,我的连接字符串位于 appsettings.json 中,如下所示:

.Net 实体框架代码

{
  "ConnectionStrings": {
    "Default": "server=DESKTOP-98TG6JE\\SERVER_2014;database=vega;user=sa;password=ComplexPassword!123;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建一个 DbContext,如下所示:

public class VegaDbContext : DbContext
{
     public VegaDbContext(DbContextOptions<VegaDbContext> options) : base(options)
     {}

     public DbSet<Make> Makes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 Startup.cs 中调用它,如下所示:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

如果我使用实体框架进行 CRUD,这很好,但是,我多次需要创建复杂的查询,因此我需要 SQL 存储过程。您能告诉我如何将我的“首选代码”与“.net 实体框架代码”集成吗?非常感谢。

PS如果可能的话,您可以使用我上面的代码作为示例吗?

mrt*_*tig 5

进行以下更改:

  • 在您的ConfigureServices方法中添加以下行: services.AddSingleton<IConfiguration>(Configuration);

  • 在class otherwith中InsertEmployee,添加IConfiguration构造函数参数,调用它configuration并将其设置为私有字段。

看起来应该是这样InsertEmployee的:

public int InsertEmployee(Employee employee)
{
    var sql = new SqlConnection(
        this.configuration.GetConnectionString("Default"));

   //... rest of your ADO code.
}
Run Code Online (Sandbox Code Playgroud)