当 IDENTITY_INSERT 设置为 OFF 时,无法在表“讨论的产品”中插入标识列的显式值

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

我收到标题中提到的错误。

重要

表单成功将数据提交到数据库中,但随后尝试使用另一个查询再次提交,该查询尝试同时插入产品讨论 ID,然后失败/崩溃。我的项目中没有这样的查询。是什么原因造成的?

当 IDENTITY_INSERT 设置为 OFF 时,无法在表“讨论的产品”中插入标识列的显式值。

我查看了多个论坛帖子,并搜索了互联网,但仍然无法解决该问题。

联系报告将提交至数据库,产品讨论表也将更新。联系报告工作正常,但产品讨论表出现错误。

请参阅下面的所有代码:

ContactReportController

[HttpGet]
public async Task<IActionResult> Submit()
{
    var contactReport = new ContactReport
    {
        ProductsDiscussed = new List<ProductDiscussed>
        {
            new ProductDiscussed() // Add one default item
        },
        Report_Date = DateTime.Now
    };

    // Load necessary data for the form
    await LoadFormDataAsync();
    return View(contactReport);
}

[HttpPost]
public async Task<IActionResult> Submit(ContactReport contactReport)
{
    if (User?.Identity?.IsAuthenticated == true)
    {
        if (ModelState.IsValid)
        {
            try
            {
                _logger.LogInformation("Model is valid. Adding contact report to context.");

                // Add the ContactReport to the context
                _context.ContactReports.Add(contactReport);
                await _context.SaveChangesAsync();

                // Ensure EF Core recognizes each product as a new entity
                foreach (var product in contactReport.ProductsDiscussed)
                {
                    // Set the foreign key
                    product.ReportID = contactReport.Report_Id;

                    // Mark the product as a new entity
                    _context.ProductsDiscussed.Add(product);
                }

                await _context.SaveChangesAsync();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An error occurred while saving the contact report.");
                ModelState.AddModelError("", "An error occurred while saving the report. Please try again.");
            }
        }
        else
        {
            _logger.LogWarning("Model state is invalid.");

            foreach (var error in ModelState.Values.SelectMany(v => v.Errors))
            {
                _logger.LogWarning(error.ErrorMessage);
            }
        }
    }
    else
    {
        _logger.LogWarning("User is not authenticated.");
        return Unauthorized();
    }

    // Reload data if ModelState is invalid
    await LoadFormDataAsync(); // Method to load the data needed for the form

    return View(contactReport);
}

private async Task LoadFormDataAsync()
{
    var staffList = await _context.Staff.OrderBy(s => s.Name).ToListAsync();
    ViewBag.StaffList = new SelectList(staffList, "StaffId", "Name");

    var countries = await _context.Countries.OrderBy(c => c.CountryName).ToListAsync();
    ViewBag.Countries = new SelectList(countries, "CountryCode", "CountryName");

    var productCategories = await _context.ProductCategories.OrderBy(c => c.CategoryName).ToListAsync();
    ViewBag.ProductCategories = new SelectList(productCategories, "CategoryID", "CategoryName");

    var customers = await _context.Customers.ToListAsync();
    var customerList = customers
        .Select(c => new
        {
            c.CustomerId,
            DisplayName = string.IsNullOrEmpty(c.City)
                ? $"{c.Name} {c.Surname} - {c.Country}"
                : $"{c.Name} {c.Surname} - {c.Country}, {c.City}",
            SortKey = string.IsNullOrEmpty(c.Name) ? c.Surname : $"{c.Name} {c.Surname}"
        })
        .OrderBy(c => c.SortKey)
        .ToList();
    ViewBag.CustomerList = new SelectList(customerList, "CustomerId", "DisplayName");
}

Submit.cshtml

<div id="productsContainer">
    @for (int i = 0; i < Model.ProductsDiscussed.Count; i++)
    {
        <div class="card mb-3">
            <div class="card-body">
                <div class="form-group">
                    <label asp-for="ProductsDiscussed[i].BrandProductCategoriesID">Product Category</label>
                    <select asp-for="ProductsDiscussed[i].BrandProductCategoriesID" class="form-control" asp-items="ViewBag.ProductCategories">
                        <option value="">Select a product category</option>
                    </select>
                    <span asp-validation-for="ProductsDiscussed[i].BrandProductCategoriesID" class="text-danger"></span>
                </div>

                <div class="form-group">
                    <label asp-for="ProductsDiscussed[i].Sample">Sample Used</label>
                    <select asp-for="ProductsDiscussed[i].Sample" class="form-control">
                        <option value="false">No</option>
                        <option value="true">Yes</option>
                    </select>
                    <span asp-validation-for="ProductsDiscussed[i].Sample" class="text-danger"></span>
                </div>
            </div>
        </div>
    }
</div>

<button type="button" id="addProductButton" class="btn btn-secondary mt-3">Add Another Product</button>

SQL代码:

[Products Discussed ID] [int] IDENTITY(1,1) NOT NULL,

ContactReport.cs

public ContactReport()
{
     ProductsDiscussed = new List<ProductDiscussed>();
}

// Text in-between

[NotMapped]
public List<ProductDiscussed> ProductsDiscussed { get; set; } = new List<ProductDiscussed>();

ProductDiscussed.cs

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("Products Discussed ID")]
public int ProductsDiscussedID { get; set; } // Manually managed ID

提交报告后出错:

CustomerDatabase.Controllers.ContactReportController:信息:模型有效。将联系人报告添加到上下文中。

Microsoft.EntityFrameworkCore.Database.Command:信息:执行的DbCommand [参数=[@p0='SUR238'(Nullable = false)(大小= 4000),@p1='test'(Nullable = false)(大小= 4000) 、 @p2='test' (Nullable = false) (大小 = 4000)、@p3='' (Nullable = false) (大小 = 4000)、@p4='test' (Nullable = false) (大小 = 4000) ,@p5='2024-08-12T00:00:00.0000000',@p6='test'(可为空= false)(大小= 4000),@p7='STA11'(可为空= false)(大小= 4000)] , CommandType='文本', CommandTimeout='30']
将 IMPLICIT_TRANSACTIONS 设置为关闭;
不设置计数;
插入[联系人报告]([客户 ID]、[反馈]、[跟进]、[位置]、[备注]、[报告日期]、[报告说明]、[员工 ID])
输出已插入。[Id]
值(@p0、@p1、@p2、@p3、@p4、@p5、@p6、@p7);

抛出异常:Microsoft.Data.SqlClient.dll 中的“Microsoft.Data.SqlClient.SqlException”
Microsoft.EntityFrameworkCore.Database.Command:错误:执行 DbCommand 失败 [参数=[@p0='18'、@p1='3'、@p2='195'、@p3='False']、CommandType='Text ', CommandTimeout='30']

Microsoft.EntityFrameworkCore.DbUpdateException:保存实体更改时发生错误。有关详细信息,请参阅内部异常。

Microsoft.Data.SqlClient.SqlException(0x80131904):当 IDENTITY_INSERT 设置为 OFF 时,无法在表“讨论的产品”中插入标识列的显式值。

c# asp.net-core entity-framework-core model-binding identity-column
1个回答
0
投票

数据库对您未执行的插入进行神秘投诉的两个常见原因:

  1. 触发器 - 检查表[联系人报告]上是否有任何触发器
  2. 复制 - 查看是否使用复制将数据从[联系人报告]复制到[讨论的产品]
© www.soinside.com 2019 - 2024. All rights reserved.