为什么EF4 Code First在存储对象时如此之慢?

Saa*_*aab 12 c# db4o entity-framework

我目前正在研究如何在我的Web应用程序中使用db4o存储.我很高兴db4o的工作原理.因此,当我阅读Code First方法时,我有点喜欢的是,因为使用EF4 Code First的方式与使用db4o非常相似:创建域对象(PO​​CO),将它们抛到db4o,永不回头.

但是当我进行性能比较时,EF 4的速度非常慢.我无法弄清楚原因.

我使用以下实体:

public class Recipe { private List _RecipePreparations; public int ID { get; set; } public String Name { get; set; } public String Description { get; set; } public List Tags { get; set; } public ICollection Preparations { get { return _RecipePreparations.AsReadOnly(); } }

    public void AddPreparation(RecipePreparation preparation) 
    {
        this._RecipePreparations.Add(preparation);
    }
}
Run Code Online (Sandbox Code Playgroud)

public class RecipePreparation {public String Name {get; 组; } public String Description {get; 组; } public int Rating {get; 组; public List Steps {get; 组; } public List Tags {get; 组; public int ID {get; 组; }}

为了测试性能,我新建了一个配方,并添加了50.000 RecipePrepations.然后我将对象存储在db4o中,如下所示:

IObjectContainer db = Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), @"RecipeDB.db4o");
db.Store(recipe1);
db.Close();
Run Code Online (Sandbox Code Playgroud)

这需要大约13.000(ms)

我将这些东西与EF4存储在SQL Server 2008(Express,local)中,如下所示:

cookRecipes.Recipes.Add(recipe1);
cookRecipes.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

这需要200.000(ms)

现在怎么样的db4o 15(!!!)快了EF4/SQL?我错过了EF4的秘密涡轮按钮吗?我甚至认为db4o可以更快?由于我没有初始化数据库文件,我只是让它动态增长.

Tom*_*han 3

你在循环SaveChanges() 内调用了吗?怪不得这么慢!尝试这样做:

foreach(var recipe in The500000Recipes)
{
    cookRecipes.Recipes.Add(recipe);
}
cookRecipes.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

EF 希望您进行所需的所有更改,然后调用SaveChanges 一次。这样,它可以优化数据库通信和 sql 来执行打开状态和保存状态之间的更改,忽略您已撤消的所有更改。(例如,添加 50 000 条记录,然后删除其中一半,然后命中SaveChanges只会向数据库添加 25 000 条记录。永远。)