客户模型
public class Customer
{
public int Id { get; set; }
public string? Name { get; set; }
}
以客户为财产的支付模式
public class Payment
{
public int Id { get; set; }
public string? Name { get; set; }
public Customer? Customer { get; set; }
}
数据访问:
public class DataAccess : DbContext
{
IConfiguration Configuration;
public DataAccess(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("Default"));
}
public DbSet<Customer>? Customers { get; set; }
public DbSet<Payment>? Payments { get; set; }
}
服务:
public class TestService : ITestService
{
private readonly IDbContextFactory<DataAccess> ContextFactory;
public TestService(IDbContextFactory<DataAccess> contextFactory)
{
ContextFactory = contextFactory;
}
public async Task Add(Payment entity)
{
try
{
using (var context = ContextFactory.CreateDbContext())
{
await context.Payments!.AddAsync(entity);
await context.SaveChangesAsync();
}
}
catch (Exception ex)
{
// Handle the exception (log, rethrow, etc.)
Console.WriteLine($"Error adding payment: {ex.Message}");
throw;
}
}
public async Task<List<Customer>> GetAllCustomer()
{
using (var context = ContextFactory.CreateDbContext())
{
return await context.Customers!.AsNoTracking().ToListAsync();
}
}
public async Task<List<Payment>> GetAllPayment()
{
using (var context = ContextFactory.CreateDbContext())
{
return await context.Payments!.Include(P => P.Customer).AsNoTracking().ToListAsync();
}
}
}
当我尝试插入付款时收到此错误:
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Customers”中插入标识列的显式值。
请帮忙