c#中,使用泛型仓储库,实现数据库操作的完整实例
时间: 2024-03-01 15:56:25 浏览: 67
以下是一个简单的 C# 泛型仓储库实现,用于对 Employee 实体进行增删改查等操作:
首先,我们定义 Employee 实体类:
```csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
```
接着,我们定义 EmployeeDbContext 类,继承自 DbContext:
```csharp
public class EmployeeDbContext : DbContext
{
public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
```
在 EmployeeDbContext 类中,我们定义了一个 DbSet<Employee> 属性,表示 Employee 实体对应的数据库表。
接下来,我们定义 EmployeeRepository 类,实现 IRepository<Employee> 接口:
```csharp
public class EmployeeRepository : IRepository<Employee>
{
private readonly EmployeeDbContext _dbContext;
public EmployeeRepository(EmployeeDbContext dbContext)
{
_dbContext = dbContext;
}
public void Add(Employee employee)
{
_dbContext.Employees.Add(employee);
_dbContext.SaveChanges();
}
public void Delete(Employee employee)
{
_dbContext.Employees.Remove(employee);
_dbContext.SaveChanges();
}
public void Update(Employee employee)
{
_dbContext.Employees.Update(employee);
_dbContext.SaveChanges();
}
public Employee GetById(int id)
{
return _dbContext.Employees.Find(id);
}
public IEnumerable<Employee> GetAll()
{
return _dbContext.Employees.ToList();
}
}
```
在 EmployeeRepository 类中,我们使用了 EmployeeDbContext 对象进行了数据库操作。
最后,我们在 Program 类中使用 EmployeeRepository 类进行操作:
```csharp
class Program
{
static void Main(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<EmployeeDbContext>();
optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SampleDatabase;Integrated Security=True");
using (var dbContext = new EmployeeDbContext(optionsBuilder.Options))
{
var repository = new EmployeeRepository(dbContext);
// 添加 Employee
var employee = new Employee { Name = "Tom", Age = 30, Department = "IT" };
repository.Add(employee);
// 修改 Employee
employee = repository.GetById(1);
employee.Department = "HR";
repository.Update(employee);
// 删除 Employee
employee = repository.GetById(1);
repository.Delete(employee);
// 获取所有 Employee
var employees = repository.GetAll();
foreach (var emp in employees)
{
Console.WriteLine($"{emp.Id} {emp.Name} {emp.Age} {emp.Department}");
}
}
}
}
```
上述代码中,我们通过 EmployeeRepository 对象进行了对 Employee 实体的增删改查等操作。同时,我们使用了 Entity Framework Core 和 SQL Server 数据库进行了持久化操作。
阅读全文