efcore icon indicating copy to clipboard operation
efcore copied to clipboard

EF Core 2.1 db type error

Open Cugap opened this issue 8 years ago • 7 comments

After update to .net core 2.1 i get some error when try to read all data from db table

System.InvalidOperationException: "An exception occurred while reading a database value for property 'Meters.AccessIsWrite'. The expected type was 'System.Boolean' but the actual value was of type 'System.Boolean'."

Inner exception:
InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.Byte'.

System.InvalidOperationException
  HResult=0x80131509
  Message= An exception occurred while reading a database value for property 'Meters.AccessIsWrite'. The expected type was 'System.Boolean' but the actual value was of type 'System.Boolean'.
  Source= Microsoft.EntityFrameworkCore
  Stack trace:
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource.ThrowReadValueException[TValue](Exception exception, Object value, IPropertyBase property)
   at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.<_FastQuery>d__3`1.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at CloudCenergoCollector.CenergoCollector.UpdateKnownMeters() in D:\Repos\csWeb\CloudCenergoCollector\CenergoCollector.cs:line 113
   at CloudCenergoCollector.CenergoCollector.UpdateCollectorData() in D:\Repos\csWeb\CloudCenergoCollector\CenergoCollector.cs:line 73
   at CloudCenergoCollector.CenergoCollector..ctor(cenergoContext cenergoDb, cscloudContext cloudDb, IConfiguration config, Boolean importNew) in D:\Repos\csWeb\CloudCenergoCollector\CenergoCollector.cs:line 67
   at CloudCenergoCollector.Program.Main(String[] args) in D:\Repos\csWeb\CloudCenergoCollector\Program.cs:line 67

Steps to reproduce

Just try to read data from sqlserver db on netcore 2.1, have same problem on Pomelo.EntityFrameworkCore.MySql v2.1-preview mysql db's

code that produce error:

var meters = dbContext.Meters.AsNoTracking().ToList();

tryed without "AsNoTracking" or "ToList"

Db connection:

var dbOpt = new DbContextOptionsBuilder<dbContext>();
dbOpt.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"));
var db = new dbContext(dbOpt.Options);

Model

public partial class Meters
    {
        public Meters()
        {
        }

        public int MeterId { get; set; }
        public string SerialNumber { get; set; }
        public string ComAddress { get; set; }
        public string SysAddress { get; set; }
        public DateTime? PlugDate { get; set; }
        public DateTime? TestDate { get; set; }
        public int CurTrRatio { get; set; }
        public int VolTrRatio { get; set; }
        public byte[] Parameter { get; set; }
        public bool AccessIsWrite { get; set; }
        public string AccessPassword { get; set; }
        public double? GeoAltitude { get; set; }
        public double? GeoLatitude { get; set; }
        public double? GeoLongitude { get; set; }
        public string Designation { get; set; }
        public string FiederName { get; set; }
        public float? VoltageLevel { get; set; }
        public string ActNumberInstall { get; set; }
        public string SealNumber { get; set; }
        public bool IsAlarmActive { get; set; }
        public float? LossLevelFider { get; set; }
        public string Reserve { get; set; }
        public int? ComObjectId { get; set; }
        public int? CustomerId { get; set; }
        public int DeviceTypeId { get; set; }
        public int DeviceStateId { get; set; }
        public int MeterPlugSourceId { get; set; }
        public int? GroupOneId { get; set; }
        public int? GroupTwoId { get; set; }
        public int? GroupThreeId { get; set; }
        public int? WorkerId { get; set; }
        public int? PhaseTypeId { get; set; }
    }

Type of "AccessIsWrite" field in db is TINYINT(1)

part of OnModelCreating func of dbContext:

modelBuilder.Entity<Meters>(entity =>
            {
                entity.HasKey(e => e.MeterId);

                entity.ToTable("meters");

                entity.HasIndex(e => e.ComObjectId)
                    .HasName("FK_Meters_ComObject");

                entity.HasIndex(e => e.CustomerId)
                    .HasName("FK_Meters_Customer");

                entity.HasIndex(e => e.DeviceStateId)
                    .HasName("FK_Meters_RefDeviceState");

                entity.HasIndex(e => e.DeviceTypeId)
                    .HasName("FK_Meters_RefDeviceType");

                entity.HasIndex(e => e.GroupOneId)
                    .HasName("FK_Meters_GroupsOne");

                entity.HasIndex(e => e.GroupThreeId)
                    .HasName("FK_Meters_GroupsThree");

                entity.HasIndex(e => e.GroupTwoId)
                    .HasName("FK_Meters_GroupsTwo");

                entity.HasIndex(e => e.MeterPlugSourceId)
                    .HasName("FK_Meters_RefMeterPlugSource");

                entity.HasIndex(e => e.PhaseTypeId)
                    .HasName("FK_Meters_RefPhaseType");

                entity.HasIndex(e => e.WorkerId)
                    .HasName("FK_Meters_Workers");

                entity.Property(e => e.MeterId).HasColumnType("int(9)");

                entity.Property(e => e.AccessIsWrite).HasColumnType("tinyint(1)");

                entity.Property(e => e.ComObjectId).HasColumnType("int(9)");

                entity.Property(e => e.CurTrRatio).HasColumnType("int(9)");

                entity.Property(e => e.CustomerId).HasColumnType("int(9)");

                entity.Property(e => e.DeviceStateId).HasColumnType("int(9)");

                entity.Property(e => e.DeviceTypeId).HasColumnType("int(9)");

                entity.Property(e => e.GroupOneId).HasColumnType("int(9)");

                entity.Property(e => e.GroupThreeId).HasColumnType("int(9)");

                entity.Property(e => e.GroupTwoId).HasColumnType("int(9)");

                entity.Property(e => e.IsAlarmActive).HasColumnType("tinyint(1)");

                entity.Property(e => e.MeterPlugSourceId).HasColumnType("int(9)");

                entity.Property(e => e.PhaseTypeId).HasColumnType("int(9)");

                entity.Property(e => e.PlugDate).HasColumnType("datetime");

                entity.Property(e => e.SerialNumber).IsRequired();

                entity.Property(e => e.TestDate).HasColumnType("datetime");

                entity.Property(e => e.VolTrRatio).HasColumnType("int(9)");

                entity.Property(e => e.WorkerId).HasColumnType("int(9)");

                ...
}

thats all i get after db scaffold in 2.0 net core

Further technical details

EF Core version: 2.1 Database Provider: Microsoft.EntityFrameworkCore.SqlServer v2.1 Operating system: win 10(x64) IDE: Visual Studio 2017 15.7.3

Cugap avatar Jun 07 '18 15:06 Cugap

@Cugap In 2.1, you will need to explicitly specify the column type since EF is now using a different mechanism to read the value from the database. Something like:

modelBuilder.Entity<Meters>().Property(e => e.AccessIsWrite).HasColumnType("TINYINT")

Note for triage: I'm not sure why this was working in 2.0. I'm guessing might be a result of switching from the non-typed to the typed ValueBufferFactoryFactory, but it's not clear to be exactly how it was ever working before. So it's a regression, but it's working pretty much by-design in 2.1.

ajcvickers avatar Jun 07 '18 16:06 ajcvickers

@Cugap Forgot to mention. Rather than specifying the store type explicitly, you could instead have EF infer it from a different CLR type:

modelBuilder.Entity<Meters>().Property(e => e.AccessIsWrite).HasConversion<byte>();

This should do the same thing.

ajcvickers avatar Jun 07 '18 16:06 ajcvickers

@ajcvickers, sorry, forget add to issue post, that's already in dbcontext

updated first post

tryed add ".HasConversion<byte>();" or ".HasConversion<bool>();" but it doesn't help.

Cugap avatar Jun 08 '18 06:06 Cugap

@Cugap Is that really the output from scaffolding a SQL Server database? It looks like the output from scaffolding some other kind of database? Are you scaffolding from MySQL and then using with SQL Server?

ajcvickers avatar Jun 08 '18 16:06 ajcvickers

@ajcvickers yea you are right thats realy result of scaffolding of MySQL db variant. Do you think that SQL Server scaffolding helps?

Cugap avatar Jun 08 '18 18:06 Cugap

@Cugap In general, a model created for SQL Server will not work for MySQL, or vice versa. In a lot of cases the differences are small and can be handled by using appropriate abstract APIs--for example using the HasConversion call above, which is agnostic the database being used, as opposed to the HasColumnType call which is not. The scaffolding does not attempt to do this, so the model you get out will be very specific to the database provider used to create it.

Can you scaffold from your SQL Server database and see if you are still hitting issues?

ajcvickers avatar Jun 08 '18 20:06 ajcvickers

@ajcvickers I tested this case and it works, all difference that type declaration .HasColumnType("tinyint(1)") in SqlServer is missing. It seems strange.

Cugap avatar Jun 09 '18 06:06 Cugap