实体框架无法为标识列插入显式值

问题描述 投票:0回答:1

客户模型

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”中插入标识列的显式值。

请帮忙

c# entity-framework
1个回答
0
投票

此错误意味着您正在尝试将值显式分配给数据库自动分配的列。

您可以尝试不设置表的Id值来了解场景

请参阅此处了解更多信息

© www.soinside.com 2019 - 2024. All rights reserved.