【问题标题】:ASP.Net Core 3.1 Razor Pages and CRUD operation with DapperASP.Net Core 3.1 Razor Pages 和 CRUD 操作与 Dapper
【发布时间】:2020-03-30 09:14:12
【问题描述】:

我是 ASP.Net Core 3.1 的初学者,必须在我们的项目中使用 Dapper,需要使用 Dapper 从 webform 升级到 asp.net core 3.1,因为我们在某些页面上使用了大量存储过程和 CTE 查询。我们还有很多经常查询的数据。

我处于非常初级的水平,没有 MVC 经验,所以我的重点是使用 dapper 的 ASP.Net Core 3.1 剃须刀页面,不幸的是,我无法在网上找到使用 Razor 页面和 dapper 的完整教程。大多数示例和教程都是基于 ASP.net 核心 MVC 和 EF 的。

我正在尝试将 Blazor dapper example 转换为 asp.net core razor 页面,但我一直在纠结如何在 employee.cshtml.cs 上显示数据

      using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BookListRazor.Data;
using BookListRazor.Model;

namespace BookListRazor.Pages
{
    public class EmployeeModel : PageModel
    {

        private readonly SqlConnectionConfiguration _configuration;
        public EmployeeModel(SqlConnectionConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IEnumerable<Employee> EmployeeList{ get; set; }

        public IEmployeeService _employeeService;


        public async Task OnGet()
        {

            EmployeeList = await _employeeService.GetEmployees();
        }
    }
}

我无法在EmployeeDapperService.cs 类中调用GetEmployees() 函数。我需要帮助,以便我可以列出所有员工,然后我还将从事插入和更新工作。

下面是项目的完整代码

文件夹结构和文件

-Data
--EmployeeDapperService.cs
--IEmployeeService.cs
--SqlConnectionConfiguration.cs

-Model
--Employee.cs

-Pages
--Index.cshtml
--Employee.cshtml

Startup.cs

EmployeeDapperService.cs

using Dapper;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using BookListRazor.Model;
using BookListRazor.Data;

namespace BookListRazor.Data
{
    public class EmployeeDapperService : IEmployeeService
    {
        private readonly SqlConnectionConfiguration _configuration;
        public EmployeeDapperService(SqlConnectionConfiguration configuration)
        {
            _configuration = configuration;
        }
        public async Task<bool> CreateEmployee(Employee employee)
        {
            using (var conn = new SqlConnection(_configuration.Value))
            {
                const string query = @"insert into dbo.Employees (Id,Name,Department,Designation,Company,City) values(@Id,@Name,@Department,@Designation,@Company,@City)";
                conn.Open();
                try
                {
                    await conn.ExecuteAsync(query, new { Id = Guid.NewGuid().ToString(), employee.Name, employee.Department, employee.Designation, employee.Company, employee.City }, commandType: CommandType.Text);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
            return true;
        }

        public async Task<bool> DeleteEmployee(string id)
        {
            using (var conn = new SqlConnection(_configuration.Value))
            {
                const string query = @"delete dbo.Employees where Id=@Id";
                conn.Open();
                try
                {
                    await conn.ExecuteAsync(query, new { id }, commandType: CommandType.Text);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
            return true;
        }

        public async Task<bool> EditEmployee(string id, Employee employee)
        {
            using (var conn = new SqlConnection(_configuration.Value))
            {
                const string query = @"update dbo.Employees set Name = @Name, Department = @Department, Designation = @Designation, Company = @Company, City = @City where Id=@Id";
                conn.Open();
                try
                {
                    await conn.ExecuteAsync(query, new { employee.Name, employee.Department, employee.Designation, employee.Company, employee.City, id }, commandType: CommandType.Text);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
            return true;
        }

        public async Task<List<Employee>> GetEmployees()
        {
            IEnumerable<Employee> employees;
            using (var conn = new SqlConnection(_configuration.Value))
            {
                const string query = @"select * from dbo.Employees";

                conn.Open();
                try
                {
                    employees = await conn.QueryAsync<Employee>(query, commandType: CommandType.Text);

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }

            }
            return employees.ToList();
        }

        public async Task<Employee> SingleEmployee(string id)
        {
            Employee employee = new Employee();
            using (var conn = new SqlConnection(_configuration.Value))
            {
                const string query = @"select * from dbo.Employees where Id=@Id";

                conn.Open();
                try
                {
                    employee = await conn.QueryFirstOrDefaultAsync<Employee>(query, new { id }, commandType: CommandType.Text);

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }

            }
            return employee;
        }
    }
}

IEmployeeService.cs

using BookListRazor.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BookListRazor.Data
{
    public interface IEmployeeService
    {
        Task<List<Employee>> GetEmployees();
        Task<bool> CreateEmployee(Employee employee);
        Task<bool> EditEmployee(string id, Employee employee);
        Task<Employee> SingleEmployee(string id);
        Task<bool> DeleteEmployee(string id);
    }
}

SqlConnectionConfiguration.cs

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

namespace BookListRazor.Data
{
    public class SqlConnectionConfiguration
    {
        public SqlConnectionConfiguration(string value) => Value = value;
        public string Value { get; }
    }
}

Employee.cs

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

namespace BookListRazor.Model
{
    public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public string Designation { get; set; }
        public string Company { get; set; }
        public string City { get; set; }

    }
}

Startup.cs部分代码

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


services.AddTransient<IEmployeeService, EmployeeDapperService>();
var sqlConnectionConfiguration = new SqlConnectionConfiguration(Configuration.GetConnectionString("SqlDbContext"));
        services.AddSingleton(sqlConnectionConfiguration);
        services.AddControllersWithViews();
        services.AddRazorPages().AddRazorRuntimeCompilation();

    }

Employee.cshtml.cs

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BookListRazor.Data;
using BookListRazor.Model;

namespace BookListRazor.Pages
{
    public class EmployeeModel : PageModel
    {

        //for Dapper
        private readonly SqlConnectionConfiguration _configuration;
        public IEnumerable<Employee> EmployeeList{ get; set; }

        public readonly IEmployeeService _employeeService;

        public async Task OnGet()
        {
            // Employees = await employees.

            // Employees = await 

            EmployeeList = await _employeeService.GetEmployees();
        }
    }
}

【问题讨论】:

  • 从您上面的图片和 VisualStudio intellicense 我感觉您正在尝试调用实例方法而没有EmployeeDapperService 的实例。如果是这种情况,您需要从控制器的构造函数中注入它,并在您的启动 ConfigureServices 中添加一个瞬态映射,例如 services.AddTransient&lt;IEmployeeService,EmployeeDapperService&gt;();

标签: c# asp.net asp.net-core razor


【解决方案1】:

从您上面的图片和 VisualStudio intellicense 我感觉您正在尝试调用实例方法而没有 EmployeeDapperService 的实例。

如果是这种情况,您需要从employee.cshtml.cs 页面模型的构造函数中注入它,并在您的启动ConfigureServices 中添加一个瞬态映射,例如services.AddTransient&lt;IEmployeeService,EmployeeDapperService&gt;();

编辑

Employee.cshtml.cs


    public class EmployeeModel : PageModel
    {
        public IEnumerable<Employee> Employees { get; set; }
        public IEmployeeService EmployeeService { get; }

        public EmployeeModel(IEmployeeService employeeService) {
            EmployeeService = employeeService ?? throw new ArgumentNullException(nameof(employeeService));
        }

        public async Task OnGet()
        {
           Employees = await EmployeeService.GetEmployees();
        }
    }

【讨论】:

  • 是的,可能是这样..让我试试..因为这个原因,我几乎添加了所有代码..
  • 我确实添加了services.AddTransient&lt;IEmployeeService,EmployeeDapperService&gt;();,但我在员工、cshtml .cs 页面页面中没有得到任何东西
  • @Learning 你还需要在你的employee.cshtml.cs 中引入一个属性,就像public IEmployeeService EmployeeService { get; set; } 一样,并通过构造函数注入来注入它。然后,不要直接使用类名EmployeeDapperService,而是使用属性来调用您的数据访问方法GetEmployees(); 等。
  • 你能告诉我完整的代码吗,因为我按照你的指示,但它不起作用..
  • @Learning 在我在上面的编辑中创建的构造函数中放置了一个断点。并查看框架是否为您提供了 IEmployeeService 的实例供您使用。
猜你喜欢
  • 2021-04-28
  • 2020-11-23
  • 2018-10-29
  • 2020-08-12
  • 2020-11-21
  • 2018-03-30
  • 2020-07-19
  • 2019-06-28
  • 2020-11-13
相关资源
最近更新 更多