【问题标题】:Why isn't EntityFramework adding my objects?为什么 EntityFramework 不添加我的对象?
【发布时间】:2022-01-07 10:36:33
【问题描述】:

我正在使用AutoBogus 测试数据填充内存数据库,如下所示:

// Create dummy data.
var goalFaker = new AutoFaker<Goal>()
    .RuleFor(g => g.Id, f => f.IndexFaker + 1); // +1 for the non-zero primary key.
var goals = goalFaker.Generate(10);

// Use a dummy in-memory database instead of a real one.
var options = new DbContextOptionsBuilder<GoalContext>()
    .UseInMemoryDatabase(databaseName: "TestDatabase")
    .Options;

// Save our dummy data to our dummy database.
using (var context = new GoalContext(options))
{
     context.AddRange(goals);
     context.SaveChanges();
}

但是,数据永远不会保存!它完全被忽略了。

我做错了什么?如何让我的测试数据在测试中持续存在?

【问题讨论】:

    标签: c# entity-framework unit-testing dbcontext


    【解决方案1】:

    我遇到的问题是Goal 是一个抽象类。一旦我切换到虚拟化具体实现,问题就消失了。

    // Create dummy data.
    var goalFaker = new AutoFaker<SmartGoal>() // <--- Swap in concrete SmartGoal for abstract Goal.
        .RuleFor(g => g.Id, f => f.IndexFaker + 1);
    var goals = goalFaker.Generate(10);
    
    // Use a dummy in-memory database instead of a real one.
    var options = new DbContextOptionsBuilder<GoalContext>()
        .UseInMemoryDatabase(databaseName: "TestDatabase")
        .Options;
    
    // Save our dummy data to our dummy database.
    using (var context = new GoalContext(options))
    {
         context.AddRange(goals);
         context.SaveChanges();
    }
    

    【讨论】:

    • 那很快..
    • @CaiusJard 我使用了“回答我自己的问题”选项,这很自然。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多