这篇文章为.NET Core Mysql EF主键只增踩坑记录。在 .NET Core Mysql EF 走的路越多,遇到的坑就愈多。
按照Framework管理,先创建一个Entity。
[Table("Device_SetUpdateLog")]
public class DeviceSetUpdateLog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[MaxLength(200)]
public string Name { get; set; }
[MaxLength(100)]
public string Date { get; set; }
public int CreateTime { get; set; }
}
然后在DbContent中添加DbSet。
按道理,应该就没问题了。如果在EntityFramework下,那确实是没问题的,能够正常写入数据并设置主键自增。但是如果是跑在EntityFrameworkCore,恭喜,喜获一个错误:
错误堆栈:
System.Exception: Init db data failed, error is An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.MissingFieldException: Field not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource.ThrowReadValueExceptionMethod'.
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Expression indexExpression, TypeMaterializationInfo materializationInfo, Boolean box)
at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable1 source, Func
3 selector)+MoveNext()
at System.Collections.Generic.LargeArrayBuilder1.AddRange(IEnumerable
1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__10_0(CacheKey k)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func
2 valueFactory)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ConsumeResultSetWithPropagation(Int32 commandIndex, RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(RelationalDataReader reader)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(RelationalDataReader reader)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func
3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Common.Data.Entity.ELDbDataInitializer.Initialize() in C:UserssysrusourcereposeftestCommon.Data.EntityELDbDataInitializer.cs:line 75
--- End of inner exception stack trace ---
at eftest.Program.Main(String[] args) in C:UserssysrusourcereposeftesteftestProgram.cs:line 29
分析这个错误信息也是死活找不出错在上面地方。
再仔细一看,关键词“Field not found”,而我插入的数据是这样的:
new DeviceSetUpdateLog()
{
Name = "设备发现",
Date = "2018/02/07",
CreateTime = nowUnixTime,
}
少了一个ID字段,因为ID字段设置了只增,写入数据后会自动设置,按道理是不用管的。但是鉴于此处出现了错误,我就手动指定了ID,现在插入的数据是这样的。
new DeviceSetUpdateLog()
{
ID = 1,
Name = "设备发现",
Date = "2018/02/07",
CreateTime = nowUnixTime,
}
hi,数据居然写进去了,也没有出现错误。至此算是搞明白问题出在什么位置了。
但是那么多表主键都是自增的,而且不可以单独编写ID自增的代码呀(也不是不可以,实在没有办法的情况下)。
然后就用关键词Identity搜索Nuget,或许有小惊喜哦。没想到还真让我找到了。包“Microsoft.AspNetCore.Identity.EntityFrameworkCore”
抱着司马当活马医的想法安装好。成了,在不指定ID值的情况下,可以插入数据。
文章评论