首页 > 解决方案 > Sqlite/SQLServer 提供程序差异

问题描述

我在使用 sqlite 提供程序编写集成测试时遇到了一些麻烦。

如果我将实体树附加到我的 DbContext,我会破坏关系(与 SqlServer 提供程序相同)。

有关详细信息,请参阅示例。

为了精确起见,3 个表的 PK 为 Id + TenantId。TenantId 仅在 SaveChangesAsync 方法中设置,具体取决于连接的用户。

如果我想让它在 sqlite 上工作,我必须在 3 个对象上设置 TenantId,然后再将它们附加到上下文......为什么这与 SQL Server 提供程序不同?


public class Store {
    public int Id { get; set; }
    public int TenantId { get; set; }

    public List<Product> Products { get; set; }
}

public class Product {
    public int Id { get; set; }
    public int TenantId { get; set; }

    public Store Store { get; set; }
    public int StoreId { get; set; }

    public Category Category { get; set; }
    public int CategoryId { get; set; }
}

public class Category {
    public int Id { get; set; }
    public int TenantId { get; set; }

    public List<Product> Products { get; set; }
}

[Test]
public void Test_Create(){
    var store = new Store();
    store.Products = new List<Product>();

    var product = new Product();
    product.Category = new Category();

    store.Products.Add(product);

    dbContext.Stores.Add(store);

    // fails, product is detached from the Store after attaching to DbContext
    Assert.Single(store.Products);
}

标签: sqliteentity-framework-coreef-core-2.2

解决方案


推荐阅读