Problem
In my app, I use SQL Server:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString));
but when I use InMemoryProvider in my unit tests:
[TestInitialize]
public void Initialize()
{
Services = new ServiceCollection();
Services.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase("MyDbContext"), ServiceLifetime.Transient);
ServiceProvider = Services.BuildServiceProvider();
}
I'm getting:
System.NotSupportedException: The 'PersonId' on entity type 'Person' does not have a value set and no value generator is available for properties of type 'decimal'. Either set a value for the property before adding the entity or configure a value generator for properties of type 'decimal'.
Question
Where do I configure custom ValueGenerator for PersonId property, so that it will be used only in my test project where I use InMemoryProvider?
What I have
I have MS SQL Server Database and a table with autoincrement identity column of type numeric(10, 0).
CREATE TABLE [dbo].[People](
[Person ID] [numeric](10, 0) IDENTITY(100000000,1) NOT NULL,
CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED
and the EF Code
[Column("Person ID", TypeName = "numeric(10, 0)")]
public decimal PersonId { get; set; }
public class MyDbContext
{
public OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>(entity =>
{
entity.Property(e => e.PersonId).ValueGeneratedOnAdd();
});
}
}
My application uses SQL Server, but I want to setup EF to use InMemoryProvider in tests. The Custom ValueGenerator should be used only in tests
decimal
and notint
which is working?