【问题标题】:SQLiteNetExtensions - InsertWithChildrenAsync not working when Foreign Key constraint exists on child tableSQLiteNetExtensions - 当子表上存在外键约束时,InsertWithChildrenAsync 不起作用
【发布时间】:2019-03-05 15:56:03
【问题描述】:

Xamarin.Forms 项目,使用 SQLiteNetExtensions 2.0.0 和 sqlite-net-pcl 1.5.231

我正在尝试将新记录插入到 sqlite 数据库中。当我在子表上删除 NOT NULL 和外键约束时,我的场景有效。当我重新添加约束时,我得到以下异常:

SQLite.SQLiteException: '约束'

  • 父模型
[Table("RetailItem")]

public class RetailItemDTO

{

    [PrimaryKey, AutoIncrement]
    public int RetailItemId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public bool Taxable { get; set; }

    public int DepartmentId { get; set; }

    public int RetailTypeId { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<RetailItemRetailerPriceDTO> Prices { get; set; }
}
  • 儿童模型
[Table("RetailItemRetailerPrice")]

public class RetailItemRetailerPriceDTO

{

    [PrimaryKey, AutoIncrement]
    public int RetailItemRetailerPriceId { get; set; }

    [ForeignKey(typeof(RetailItemDTO)), NotNull]
    public int RetailItemId { get; set; }

    public int RetailerId { get; set; }

    public decimal Price { get; set; }
}
  • 插入/更新逻辑
public async Task Save(RetailItem entity)

{

    var dto = GetDTOFromBusinessModel(entity);

    if (dto.RetailItemId == 0)
    {
        await _sqliteRepository.Database.InsertWithChildrenAsync(dto, true);

        entity.Id = dto.RetailItemId;
    }
    else
        await _sqliteRepository.Database.InsertOrReplaceWithChildrenAsync(dto, true);
}

如果我有一个现有的 RetailItem,并带有新添加的价格,则 InsertOrReplaceWithChildrenAsync 调用 正常工作 失败并显示以下内容:SQLite.NotNullConstraintViolationException: 'NOT NULL constraint failed: RetailItemRetailerPrice.RetailItemId'

每当我使用新的 RetailItemRetailerPrice 添加新的 RetailItem 时,都会发生约束异常。

如果我在 RetailItemRetailerPrice 表上删除 RetailItemId 的 NOT NULL 和外键约束,那么这两个调用都可以工作。

我想在我的桌子上保持适当的约束。

我是否遗漏了一些可以使我的场景正常工作的属性?

【问题讨论】:

    标签: xamarin.forms


    【解决方案1】:

    您已设置RetailItemIdnot null ,当您在RetailItemRetailerPrice 表中添加新项目时,您必须为新价格设置RetailItemId。

    [ForeignKey(typeof(RetailItemDTO)), NotNull] public int RetailItemId { get; set; }

    如果您不想在表上保留约束。在RetailItemRetailerPrice表中添加新项目之前,可以先查询RetailItem表,得到RetailItemId,最后在RetailItemRetailerPrice表中添加这个新项目。

    【讨论】:

    • 如果我从属性中删除 NotNull 属性,仍然会发生约束错误。我认为我不需要在插入后查找 RetailItemId 并在子类上手动更新它。我认为这个框架会为我做到这一点。如果我删除了 RetailItemRetailerPrice 表上的 NotNull 和 ForeignKey 约束,那么框架会插入具有正确 RetailItemId 的记录,而无需我在插入父记录后进行查找并在类上设置 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2011-04-22
    • 2019-07-15
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多