0

尝试在 MySQL 数据库中插入数据时出现 DbUpdateException。已使用 Pomelo.EntityFrameworkCore.MySql 包从数据库中搭建模型,该项目是在 .net core 2.1 中创建的

堆栈跟踪:

异常消息:无法添加或更新子行:外键约束失败 ( HMEBooking. Invoice, CONSTRAINT Invoice_ibfk_7FOREIGN KEY ( BookingId) REFERENCES Booking(Id)在删除时没有操作更新没有操作)堆栈跟踪:在 C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 中的 MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs 中的 MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) 的 93:MySql.Data.MySqlClient.MySqlDataReader.CreateAsync 的第 328 行( MySqlCommand 命令,CommandBehavior 行为,IOBehavior ioBehavior)在 C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:MySqlConnector.Core.TextCommandExecutor.ExecuteReaderAsync 的第 313 行(字符串 commandText,MySqlParameterCollection parameterCollection,CommandBehavior 行为, IOBehavior IOBehavior,C:\projects\mysqlconnector\src\MySqlConnector\Core\TextCommandExecutor.cs 中的 CancellationTokenCancellationToken):C:\projects\mysqlconnector\src\MySqlConnector\MySql 中 MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior 行为)的第 73 行.Data.MySqlClient\MySqlCommand.cs:Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute 的第 168 行(IRelationalConnection 连接,DbCommandMethod 执行方法,IReadOnlyDictionary执行(IRelationalConnection 连接,DbCommandMethod 执行方法,IReadOnlyDictionary执行(IRelationalConnection 连接,DbCommandMethod 执行方法,IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues) 在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection 连接)

有 Booking、BookingDetail 和 Invoice 模型。BookingDetail 与 Booking 有关系,Invoice 与 Booking 和 BookingDetail 有关系。

向数据库添加条目时出现错误无法添加或更新子行:外键约束失败。但是当我在非 .net 核心应用程序中使用相同的模型时,它可以工作

如果我在某个地方出错,请告诉我。感谢您的帮助。

以下是使用的模型

public partial class Booking
{
    public Booking()
    {
        BookingDetail = new HashSet<BookingDetail>();
        Invoice = new HashSet<Invoice>();
    }

    [Column(TypeName = "bigint(20)")]
    public long Id { get; set; }
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string TempId { get; set; }

    [InverseProperty("Booking")]
    public ICollection<BookingDetail> BookingDetail { get; set; }
    [InverseProperty("Booking")]
    public ICollection<Invoice> Invoice { get; set; }
}
public partial class BookingDetail
{
    public BookingDetail()
    {
        Invoice = new HashSet<Invoice>();
    }

    [Column(TypeName = "bigint(20)")]
    public long Id { get; set; }
     [Required]
    [Column(TypeName = "varchar(50)")]
    public string CreatedBy { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime CreatedOn { get; set; }
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string ModifiedBy { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime ModifiedOn { get; set; }
    [Column(TypeName = "bigint(20)")]
    public long BookingId { get; set; }       
    [ForeignKey("BookingId")]
    [InverseProperty("BookingDetail")]
    public Booking Booking { get; set; }
    [InverseProperty("BookingDetail")]
    public ICollection<Invoice> Invoice { get; set; }
}
 public partial class Invoice
{

    [Column(TypeName = "bigint(20)")]
    public long Id { get; set; }
    [Column(TypeName = "bigint(20)")]
    public long BookingId { get; set; }
    [Column(TypeName = "bigint(20)")]
    public long BookingDetailId { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime CreatedOn { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime CreatedBy { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime ModifiedOn { get; set; }
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string ModifiedBy { get; set; }
    [ForeignKey("BookingId")]
    [InverseProperty("Invoice")]
    public Booking Booking { get; set; }
    [ForeignKey("BookingDetailId")]
    [InverseProperty("Invoice")]
    public BookingDetail BookingDetail { get; set; }
}
  public class Class1
{
    HMEBookingContext context = new HMEBookingContext();
    #region declarations
    public long BookingId { get; set; }
    public string CustomerEmailId { get; set; } = "admin@holidayme.com";      
    #endregion
    Random rnd = new Random();
    public void insert()
    {
        try
        {
            Booking booking = new Booking();
            booking.TempBookingId = BookingRefNumber.ToString();

            var bookingDetail = new List<BookingDetail>();
            BookingDetail detail = new BookingDetail();
            detail.CreatedBy = CustomerEmailId;
            detail.CreatedOn = DateTime.Now;
            detail.ModifiedBy = "1";
            detail.ModifiedOn = DateTime.UtcNow;
            detail.BookingStatusId = 1;

            var invoices = new List<Invoice>();
            Invoice invoice = new Invoice();
            invoices.Add(invoice);
            detail.Invoice = invoices;



            bookingDetail.Add(detail);

            booking.BookingDetail = bookingDetail;

            context.Add(booking);
            context.SaveChanges(true);
            BookingId=booking.Id
        }
        catch(DbUpdateException upd)
        {


        }

        catch(Exception ex)
        {

        }
    }



}

在 booking-bookingDetail、booking-invoice、bookingDetail - invoice 之间有一对多的关系

EF Core 版本:2.1 数据库提供程序:Pomelo.EntityFrameworkCore.MySql IDE:Visual Studio 2017

4

1 回答 1

0

错误是Invoice记录具有无效的值Invoice.BookingId

查看您的测试代码,您创建了一个Invoice对象,invoice; 您永远不会分配invoice.Booking属性,也不会添加invoicebooking.Invoices集合中,因此两者之间没有建立关系,因此使用的是默认值,Invoice.BookingId并且该 PK 值在 table 中不存在Booking

分配bookinginvoice.Booking或添加invoicebooking.Invoices,这个错误应该消失。

然而,这个解决方案并没有纠正设计缺陷——Invoice引用Bookings 和BookingDetails 和BookingDetails 可以引用不同的Booking记录,从而导致数据不一致。应该存在一个单一的函数依赖关系InvoiceInvoice -> BookingDetail或者Invoice -> Booking,而不是两者。

于 2018-09-17T20:54:08.887 回答