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.
This is a really simple and easy to read approach, though it may not be what your looking for:
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.