1

I would like to execute queries in Entity Framework that use Local tracked entities when searching before hitting the database. I have written a complex routine that populates a repository/database, and now when I use Entity Framework it will not use entities that have already been added but have not been saved yet. This snippet of code should therefore only add a single Category to the database, instead of adding n.

using (Db Db = new Db()) {
    for (int i = 0; i < 10; i++) {
        Category Category = Db.Categories.SingleOrDefault(x => x.Name == "Hello");
        if (Category == null) {
            Category = Db.Categories.Create();
            Category.Name = "Hello";
            Db.Categories.Add(Category);
            Console.WriteLine("Adding item...");
        }
    }
}

How would I go about doing this? I have an abstraction that allows me to change the provider from the IQueryable, which I tried to use to hit the Local collection first. I had no success. Please do help.

Deathspike
  • 8,582
  • 6
  • 44
  • 82
  • 1
    I'm curious. How would you plan to query entities that have not yet been saved? Any database generated id's would be 0, because they haven't been created yet. So there's no identities. Certainly you could query other things, but it just seems hackish and poor practice. Why not just keep your own collection of items and use linq to objects against it? – Erik Funkenbusch Aug 08 '12 at 22:50

1 Answers1

1

This is a really simple and easy to read approach, though it may not be what your looking for:

using (Db Db = new Db()) {
    var newCategories = new List<Category>();
    for (int i = 0; i < 10; i++) {
        Category category = newCategories.SingleOrDefault(x => x.Name == "Hello");
        if (category == null) {
            category = Db.Categories.SingleOrDefault(x => x.Name == "Hello");
            if (category == null) {
                category = Db.Categories.Create();
                category.Name = "Hello";
                Db.Categories.Add(category);
                newCategories.Add(category);
                Console.WriteLine("Adding item...");
            }
        }
    }
}

Writing your own IQueryable provider is a very involved task.

Edit: I found this post which goes into more detail about why what you are trying to do doesn't work.

Thought I don't know what your particular situation is here, you should try to remove duplicates from your collection before querying into the data store. The above solution does this at the same time.

Hope this helps.

Community
  • 1
  • 1
Jay
  • 6,224
  • 4
  • 20
  • 23