问题描述
我正在尝试使用EFCore代码优先的方法来创建和填充数据库。我有两个类(度量,说明),它们从基类(间隔)继承,基类具有一个属性,该属性本身就是一个类(SectionInfo)。迁移和更新数据库运行平稳,但是当我尝试添加我的Measurement记录时,我不断收到错误消息:“当IDENTITY_INSERT设置为OFF时,无法在表'Sections'中为Identity列插入显式值。”
根据我的收集,EFCore为描述,度量和部分创建了一个表,用于存储基础对象。当我将数据上传到数据库时,我的工作流程是先将描述添加到上下文中,然后保存更改。当我检查数据库时,我看到每个Description及其SectionInfo存储在适当的表中。但是,当我创建一个新的上下文时,将我的Measurements添加到其中,然后尝试使用context.SaveChanges()会出现标识列错误。
当我查看准备好在其上下文实例中上传的测量值时,我发现其ID属性已经自动递增。因此,我认为EFCore试图在Sections表中插入ID为“ 10”的SectionInfo(例如)的Measurement,但由于IDCore已经创建了ID,因此已经存在ID为“ 10”的SectionInfo之前我传入了一堆Description对象及其SectionInfos。
我要说的是,我不会在代码中设置/更改/触摸任何类中的Id列,只是希望EFCore可以自动增加值。
此外,SectionInfo对象与Descriptions和Measurements之间的对象也不相同。也就是说,两者之间没有关系。
我想知道如何调整课程以绕过此错误。或者,如果可以仅在我的Measurement类中限制SectionInfo属性,以使其不被映射和上传(即,不对仅一种类型的子类从基类映射继承的属性),我已经简化了类,但希望保留我问题的实质和相关信息。请让我知道我是否缺少任何东西。
public class Interval
{
[NotMapped]
public SectionInfo Section {get;set;}
}
public class Description: Interval
{
[Key]
public int Id {get;set;}
public string DescriptionName {get;set;}
public List<Measurement> Measurements {get;set;}
public Description
{
this.SectionInfo = SomeSectionInfoObject; //These are not the same objects as the Measurement SectionInfos
}
}
public class Measurement: Interval
{
[Key]
public int ID {get;set:}
public string MeasurementName {get;set;}
public Description {get;set;}
public Measurement
{
this.SectionInfo = SomeSectionInfoObject; //These are not the same objects as the Description SectionInfos
}
}
public class SectionInfo
{
[Key]
public int ID {get;set;}
public string Site {get; set;}
public string Section {get;set;}
}
My DBContext class:
class DescDBContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UsesqlServer("myConnectionString");
}
public DbSet<Description> Descriptions { get; set; }
public DbSet<Measurement> Measurements { get; set; }
public DbSet<SectionInfo> Sections { get; set; }
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)