Problem in ReadStoreGeneratedValue when inserting new entity
I can't seem to add a specific entity to my DbContext. EF Core will throw an ArgumentException (see below)
I actually tried to isolate the entities and cofigurations to reproduce this issue but that has not been succesful yet.
I have added the code below and hope that someone has seen this error before and can give me some kind of clue because I don't know where to look anymore.
Exception message:
Exception has been thrown by the target of an invocation.
Stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMapFactoryFactory.Create(IKey key)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateIdentityMap(IKey key)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
at Travel.DataAccess.Repositories.TestRepository.Add[T](T item) in C:\Projects\Techorama\travelapp\Travel.API\Travel.DataAccess\Repositories\TestRepository.cs:line 20
at Travel.Application.TestService.Add[T](T item) in C:\Projects\Techorama\travelapp\Travel.API\Travel.Business\ITestService.cs:line 24
at Travel.API.Controllers.TestController.Test() in C:\Projects\Techorama\travelapp\Travel.API\Travel.API\Controllers\TestController.cs:line 38
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
inner exception:
Exception message:
Exception has been thrown by the target of an invocation.
Stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyAccessorsFactory.Create(IPropertyBase propertyBase)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.DependentKeyValueFactoryFactory.CreateSimple[TKey](IForeignKey foreignKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.KeyValueFactoryFactory.CreateSimpleFactory[TKey](IKey key)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.KeyValueFactoryFactory.Create[TKey](IKey key)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Metadata.Internal.Key.GetPrincipalKeyValueFactory[TKey]()
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMapFactoryFactory.CreateFactory[TKey](IKey key)
inner exception:
Exception message:
Expression of type 'System.Nullable`1[System.Int32]' cannot be used for parameter of type 'System.Int32' of method 'Int32 ReadStoreGeneratedValue[Int32](Int32, Int32)' Parameter name: arg0
Stack trace:
at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1)
at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyAccessorsFactory.CreateCurrentValueGetter[TProperty](IPropertyBase propertyBase, Boolean useStoreGeneratedValues)
at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyAccessorsFactory.CreateGeneric[TProperty](IPropertyBase propertyBase)
Steps to reproduce
The following code works in isolation, but my code first migration for the tables involved look exactly the same as in my project where I am encountering this error...
public class Foo
{
private Foo() { }
public Foo(string name, string barCode)
{
Name = name;
_barCode = barCode;
}
public int Id { get; private set; }
public string Name { get; private set; }
public Bar Bar { get; private set; }
private string _barCode;
}
public class FooTypeConfig : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.Property(x => x.Name).HasMaxLength(100).IsRequired();
builder.Property<string>("BarCode").HasField("_barCode").HasColumnName("BarCode");
builder.HasOne(x => x.Bar).WithMany().HasForeignKey("BarCode").IsRequired();
}
}
public class Bar
{
private Bar() { }
public Bar(string code, string name)
{
Code = code;
Name = name;
}
public string Code { get; private set; }
public string Name { get; private set; }
}
public class BarTypeConfig : IEntityTypeConfiguration<Bar>
{
public void Configure(EntityTypeBuilder<Bar> builder)
{
builder.HasKey(x => x.Code);
builder.Property(x => x.Code).HasMaxLength(3);
builder.Property(x => x.Name).HasMaxLength(100).IsRequired();
}
}
var bar = new Bar("BAR", "test");
_context.Set<Bar>().Add(bar);
_context.SaveChanges();
var foo = new Foo("test", bar.Code);
_context.Set<Foo>().Add(foo); // Error is thrown here
_context.SaveChanges();
Further technical details
EF Core version: 2.0.1 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows 10 IDE: Visual Studio 2017 15.4.0
@Schaemelhout Unfortunately there is not much we can do here without a runnable project/solution or full code listing that reproduces what you are seeing. We have speculated that it might have something to do with the way backing fields are being used, if that helps narrow it down at all.
Found it! I had another entity that had a nullable field to indicate an optional foreign key to my Foo table, but I accidentally forgot to define the shadow property nullable as well.
I also realise that StackOverflow might have been a better place for this issue, as this is not an issue with the framework itself.
Thanks for the help and keep up the good work!