I'm using the Unit of Work pattern that calls dbcontext.SaveChanges after everything has executed on a webapi request. In part of the request, I add a new customer to the dbcontext.
dbContext.Customers.Add(new Customer());
Later in the request( usually inside of a domain event handler), I'm using the same dbcontext to pull the customer back out.
_dbContext.Customers.FirstOrDefault(x => x.Id == id);
public abstract class Customer
{
public Customer()
{
Id = Guid.NewGuid();
}
}
I've verified that dbContext.Customers.Local has the object that I'm expecting, but it doesn't seem to be fetching the local object out. Could this be caused by the fact that Customer is an abstract class, implemented by DirectCustomer and InDirectCustomer?
Why? Can I change this behavior through configuration? Maybe I have to merge the local and database results( kinda hacky ).
Update:
class Program
{
static void Main(string[] args)
{
MyDbContext context = new MyDbContext();
Guid customerGuid = Guid.NewGuid();
context.Customers.Add(new DirectCustomer()
{
Id = customerGuid
});
// This does not work, customerFromLocal1 is null
var customerFromLocal1 = context.Customers.FirstOrDefault(x => x.Id == customerGuid);
// This does work, customerFromLocal2 is NOT null
var customerFromLocal2 = context.Customers.Find(customerGuid);
}
}
public class MyDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.\\sqlexpress;integrated security=true;database=EFCoreDeepDive2");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<DirectCustomer>();
builder.Entity<IndirectCustomer>();
}
}
public abstract class Customer
{
public Guid Id { get; set; }
}
public class DirectCustomer : Customer
{
}
public class IndirectCustomer : Customer
{
public Guid ParentCustomerId { get; set; }
}