C# 4.0 实体框架核心2.1:指定字段';型号';找不到属性';型号';关于实体类型';条形码设备';
我需要使用代码优先的方法通过Entity Framework Core 2.1生成数据库,但我遇到以下错误:C# 4.0 实体框架核心2.1:指定字段';型号';找不到属性';型号';关于实体类型';条形码设备';,c#-4.0,entity-framework-core,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; }
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; }
}
公共类条码设备
{
公共整数序列号{get;set;}
公共字符串模型{get;set;}
公共虚拟ICollection 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");
}
}
公共类条码设备配置:IEntityTypeConfiguration
{
公共void配置(EntityTypeBuilder)
{
builder.HasKey(x=>x.SerialNumber);
builder.Property(t=>t.Model)
.IsRequired()
.HasField(“模型”);
}
}
和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; }
}
公共类segrationdbcontext:DbContext,IDisposable
{
公共隔离DBContext(DbContextOptions选项):基本(选项)
{ }
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.ApplyConfiguration(新的条形码设备配置());
}
公共数据库集条形码设备{get;set;}
}
最后是配置
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SegregationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddMvc();
}
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“默认”));
services.AddMvc();
}
问题在于这一流畅的配置行:
.HasField("Model")
HasField
用于在支持字段名称不符合时为正在配置的属性指定
但是您的Model
属性是auto属性,并且没有名为Model
的支持字段,因此存在异常
因此,要么删除该行,例如
builder.Property(t => t.Model)
.IsRequired();
或者,如果要强制使用名称未知的备份字段(自动属性就是这种情况),请改用UsePropertyAccessMode
方法,例如
builder.Property(t => t.Model)
.IsRequired()
.UsePropertyAccessMode(PropertyAccessMode.Field);