Entity Framework Core 2.1 : The specified field 'Model' could not be found for property 'Model' on entity type 'BarCodeDevice'

c#-4.0 entity-framework-core

Question

I need to use Code First approach to generate Database by Entity Framework Core 2.1 but I get this error:

The specified field 'Model' could not be found for property 'Model' on entity type 'BarCodeDevice'.

Here are the classes I have used to do so

public class BarCodeDevice
    {
        public int SerialNumber { get; set; }
        public string Model { get; set; }
        public virtual ICollection<ClientBarCodeDevice> ClientBarCodeDeviceList { get; set; }
    }

And the configuration class

public class BarCodeDeviceConfiguration : IEntityTypeConfiguration<BarCodeDevice>
    {
        public void Configure(EntityTypeBuilder<BarCodeDevice> builder)
        {
            builder.HasKey(x => x.SerialNumber);
            builder.Property(t => t.Model)
              .IsRequired()
              .HasField("Model");
        }
    }

And The DbContext Class

public class SegregationDbContext : DbContext, IDisposable
    {
        public SegregationDbContext(DbContextOptions<SegregationDbContext> options) : base(options)
        { }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {                        
            modelBuilder.ApplyConfiguration(new BarCodeDeviceConfiguration());            
        }

        public DbSet<BarCodeDevice> BarCodeDevices { get; set; }
    }

And finally the configuration

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<SegregationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
            services.AddMvc();
        }
1
1
11/25/2018 10:14:19 AM

Accepted Answer

The problem is this fluent configuration line:

.HasField("Model")

HasField is used to specify the backing field for the property being configured, when the backing field name does not conform to the conventions.

But you Model property is auto property and there is no backing field called Model, hence the exception.

So either remove that line, e.g.

builder.Property(t => t.Model)
    .IsRequired();

or if you want to force using the backing field with unknown name (which is the case with auto properties), use UsePropertyAccessMode method instead, e.g.

builder.Property(t => t.Model)
    .IsRequired()
    .UsePropertyAccessMode(PropertyAccessMode.Field);
5
11/25/2018 11:19:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow