不使用EF框架实现数据库增删改查

创建一个通用的数据访问层 (DAL) 类,让所有需要操作数据库的 DAL 类都继承这个基类,以实现通用的增删改查方法。下面是一个简单的示例展示如何实现这样的通用基类:

public class BaseDal<T> where T : class
{
    protected string connectionString; // 数据库连接字符串

    public BaseDal(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public void Insert(T entity)
    {
        string tableName = typeof(T).Name; // 获取表名
        string insertQuery = $"INSERT INTO {tableName} ({GetColumns()}) VALUES ({GetParams()})";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(insertQuery, connection))
            {
                SetParameters(command, entity);
                command.ExecuteNonQuery();
            }
        }
    }

    public void Update(T entity)
    {
        string tableName = typeof(T).Name; // 获取表名
        string updateQuery = $"UPDATE {tableName} SET {GetUpdateParams()} WHERE Id = @Id";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(updateQuery, connection))
            {
                SetParameters(command, entity);
                command.ExecuteNonQuery();
            }
        }
    }

    public void Delete(int id)
    {
        string tableName = typeof(T).Name; // 获取表名
        string deleteQuery = $"DELETE FROM {tableName} WHERE Id = @Id";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(deleteQuery, connection))
            {
                command.Parameters.AddWithValue("@Id", id);
                command.ExecuteNonQuery();
            }
        }
    }

    // 获取实体类的所有属性名
    private string GetColumns()
    {
        var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
        return string.Join(", ", properties.Select(p => p.Name));
    }

    // 获取参数列表
    private string GetParams()
    {
        var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
        return string.Join(", ", properties.Select(p => "@" + p.Name));
    }

    // 获取更新参数列表
    private string GetUpdateParams()
    {
        var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
        return string.Join(", ", properties.Select(p => $"{p.Name} = @{p.Name}"));
    }

    // 设置参数
    private void SetParameters(SqlCommand command, T entity)
    {
        var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
        foreach (var property in properties)
        {
            command.Parameters.AddWithValue("@" + property.Name, property.GetValue(entity));
        }
    }
}

在这个示例中,BaseDal<T> 是一个泛型基类,其中包含了通用的增删改方法。在这个基类中,我们使用了反射来获取实体类的属性,并根据属性动态生成 SQL 语句和设置参数。其他需要操作数据库的 DAL 类可以继承这个基类,从而实现通用的增删改查操作。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EFEntity Framework)是.NET Framework中的一种ORM(Object Relational Mapping)框架,可以用来简化数据库操作。下面是使用EF Web API进行增删改查的示例代码: 1. 增加数据: ```csharp [HttpPost] public async Task<IActionResult> AddData([FromBody] Data data) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.Data.Add(data); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetData), new { id = data.Id }, data); } ``` 2. 删除数据: ```csharp [HttpDelete("{id}")] public async Task<IActionResult> DeleteData(int id) { var data = await _context.Data.FindAsync(id); if (data == null) { return NotFound(); } _context.Data.Remove(data); await _context.SaveChangesAsync(); return NoContent(); } ``` 3. 修改数据: ```csharp [HttpPut("{id}")] public async Task<IActionResult> UpdateData(int id, [FromBody] Data data) { if (id != data.Id) { return BadRequest(); } _context.Entry(data).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.Data.Any(e => e.Id == id)) { return NotFound(); } else { throw; } } return NoContent(); } ``` 4. 查询数据: ```csharp [HttpGet("{id}")] public async Task<ActionResult<Data>> GetData(int id) { var data = await _context.Data.FindAsync(id); if (data == null) { return NotFound(); } return data; } ``` 以上是EF Web API进行增删改查的示例代码,需要注意的是,这只是示例代码,具体实现还需要根据具体的业务逻辑进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值