I can't beleave I'm the first person running into that problem, but didn't found any similar discussions in the net.
Here is the simple full code sample:
using SQLite.CodeFirst;
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Entity entity = new Entity();
Guid id = entity.Id;
using (var context = new MyDbContext())
{
context.Entities.Add(entity);
context.SaveChanges();
// this finds an entry
var item = context.Entities.Find(id);
}
using (var context = new MyDbContext())
{
// here it returns null
var item = context.Entities.Find(id);
}
}
}
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new SqliteDropCreateDatabaseWhenModelChanges<MyDbContext>(modelBuilder));
}
public MyDbContext() : base("MyConnection") {}
public DbSet<Entity> Entities { get; set; }
}
public class Entity
{
[Key]
public Guid Id { get; set; } = Guid.Parse("D46D98F3-C262-468A-9C28-83D81080CF18");
public string Name { get; set; } = "Test";
}
}
The problem is marked in the code. The first "Find" returns the new added entry.
But getting a new instance of the context, the entry is not found.
Even, if I run the application a second time, skipping the code adding the entry to the table, it won't find the item. The problem doesn't seem to be the "Find" method, because T've tried several other linq statements with the same result.
When I first fetch all items from the table before searching, then it works with "Find", but not with linq.
Here is the sample:
using (var context = new MyDbContext())
{
// this returns all items
var allItems = context.Entities.ToArrayAsync().Result;
// this finds the item
var item1 = context.Entities.Find(id);
// this doesn't find the item
var item2 = context.Entities.Where(x => x.Id == id).FirstOrDefault();
}
using (var context = new MyDbContext())
{
// this doesn't find the item
var item1 = context.Entities.Find(id);
// this also doesn't find the item
var item2 = context.Entities.Where(x => x.Id == id).FirstOrDefault();
}
Does anyone have an explanation? Changing the key to string or int instead of GUID, it works as expected.