Entity Framework Core 2.1:在实体类型“ BarCodeDevice”上找不到属性“ Model”的指定字段“ Model”

时间:2018-11-25 10:14:19

标签: c#-4.0 entity-framework-core

我需要使用“代码优先”方法通过Entity Framework Core 2.1生成数据库,但出现此错误:

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

这是我曾经使用过的类

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

和配置类

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

和DbContext类

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; }
    }

最后是配置

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<SegregationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
            services.AddMvc();
        }

1 个答案:

答案 0 :(得分:4)

问题是这条流畅的配置线:

.HasField("Model")

HasField用于在备份字段名称不符合backing field的情况下为正在配置的属性指定conventions

但是您的Model属性是自动属性,没有名为Model的后备字段,因此是例外。

因此,请删除该行,例如

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

或者如果您想强制使用名称未知的后备字段(自动属性就是这种情况),请改用UsePropertyAccessMode方法,例如

builder.Property(t => t.Model)
    .IsRequired()
    .UsePropertyAccessMode(PropertyAccessMode.Field);