EF Core 写一个员工获取或者使用积分的功能
时间: 2024-03-19 17:46:29 浏览: 100
假设你已经建立了以下模型:
```csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Points { get; set; }
}
public class Transaction
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public int Points { get; set; }
public DateTime TransactionDate { get; set; }
public bool IsRedeemed { get; set; }
}
```
你可以使用以下代码来扣除员工积分:
```csharp
public async Task DeductPoints(int employeeId, int points)
{
var employee = await _context.Employees.FindAsync(employeeId);
if (employee == null) throw new ArgumentException("Invalid employee id");
if (employee.Points < points) throw new ArgumentException("Insufficient points");
employee.Points -= points;
var transaction = new Transaction
{
EmployeeId = employeeId,
Points = -points,
TransactionDate = DateTime.UtcNow,
IsRedeemed = false
};
_context.Transactions.Add(transaction);
await _context.SaveChangesAsync();
}
```
你可以使用以下代码来为员工增加积分:
```csharp
public async Task AddPoints(int employeeId, int points)
{
var employee = await _context.Employees.FindAsync(employeeId);
if (employee == null) throw new ArgumentException("Invalid employee id");
employee.Points += points;
var transaction = new Transaction
{
EmployeeId = employeeId,
Points = points,
TransactionDate = DateTime.UtcNow,
IsRedeemed = false
};
_context.Transactions.Add(transaction);
await _context.SaveChangesAsync();
}
```
你可以使用以下代码来获取员工的所有交易历史记录(包括增加和扣除积分的记录):
```csharp
public async Task<IEnumerable<Transaction>> GetTransactionHistory(int employeeId)
{
return await _context.Transactions.Where(t => t.EmployeeId == employeeId).ToListAsync();
}
```
阅读全文