简体   繁体   English

EF Core为标识列插入显式值

[英]EF Core insert explicit value for identity column

I have problem with inserting data to database table which has foreign keys. 我有问题将数据插入到具有外键的数据库表。 As error I'm getting 我正在犯错误

Cannot insert explicit value for identity column in table 'MachineTypes' when IDENTITY_INSERT is set to OFF.Cannot insert explicit value for identity column in table 'SpareTypes' when IDENTITY_INSERT is set to OFF. 当IDENTITY_INSERT设置为OFF时,无法在表'MachineTypes'中为identity列插入显式值。当IDENTITY_INSERT设置为OFF时,不要在表'SpareTypes'中插入identity列的显式值。

BaseEntity.cs BaseEntity.cs

public abstract class BaseEntity
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Int64 Id { get; set; }

    public DateTime CreateDate { get; set; }
}

MachineType.cs MachineType.cs

public class MachineType : BaseEntity
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
}

SpareType.cs SpareType.cs

   public class SpareType : BaseEntity
    {
        [Required]
        [StringLength(25)]
        public string Name { get; set; }
    }

SparePart.cs SparePart.cs

public class SparePart : BaseEntity
{
[Required]
[StringLength(100)]
public string InternalCode { get; set; }

[StringLength(4096)]
public string Description { get; set; }

[StringLength(255)]
public string NameOnFolder { get; set; }

public decimal? Enter { get; set; }

public decimal? Exit { get; set; }

public decimal? Thickness { get; set; }

public string Band { get; set; }

public string Color { get; set; }

public bool Elastic { get; set; }

[Required]
public virtual MachineType MachineType { get; set; }

[Required]
public virtual SpareType SpareType { get; set; }
}

SparePartViewModel.cs SparePartViewModel.cs

 public class SparePartViewModel
    {
        public int Id { get; set; }

        public DateTime CreateDate { get; set; }

        [Required]
        [StringLength(100)]
        public string InternalCode { get; set; }

        [StringLength(4096)]
        public string Description { get; set; }

        [StringLength(255)]
        public string NameOnFolder { get; set; }

        public decimal? Enter { get; set; }

        public decimal? Exit { get; set; }

        public decimal? Thickness { get; set; }

        public string Band { get; set; }

        public string Color { get; set; }

        public bool Elastic { get; set; }



        [Required]
        public virtual MachineType MachineType { get; set; }

        [Required]
        public virtual SpareType SpareType { get; set; }
    }

Controller for posting 发布控制器

[Route("/api/v1/items")]
public class SparePartController : Controller
{
private IRepository<SparePart> _repoSparePart;


public SparePartController(IRepository<SparePart> repoSparePart)
{
    _repoSparePart = repoSparePart;

}

[HttpPost("")]
public async Task<IActionResult> Post([FromBody]SparePartViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var newItem = Mapper.Map<SparePart>(viewModel);
        newItem.CreateDate = DateTime.Now;

        _repoSparePart.Insert(newItem);

        if (await _repoSparePart.SaveChangesAsync())
        {
            return Created($"items/{newItem.InternalCode}", Mapper.Map<SparePartViewModel>(viewModel));
        }
    }
    return BadRequest("Failed to save.");
}

} }

AppContext.cs AppContext.cs

   public class AppContext : IdentityDbContext<ApplicationUser>
    {
        private IConfigurationRoot _config;

        public AppContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }

        public DbSet<SpareType> SpareTypes { get; set; }
        public DbSet<MachineType> MachineTypes { get; set; }
        public DbSet<SparePart> SpareParts { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<SpareType>()
                .HasIndex(s => new { s.Name })
                .IsUnique(true);

            builder.Entity<MachineType>()
                .HasIndex(s => s.Name)
                .IsUnique(true);


            base.OnModelCreating(builder);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:RndDbContextConnection"]);
        }
    }

During the posting all the data are catch correctly, but when should be inserted into database I'm getting an error. 在发布期间,所有数据都被正确捕获,但是什么时候应该插入到数据库中我得到一个错误。 在此输入图像描述

When inserting the new SparePart instance, the MachineType and SpareType references need to be fetched from the same DbContext beforehand. 插入新的SparePart实例时,需要事先从相同的DbContext中获取MachineType和SpareType引用。 Otherwise EF thinks you are trying to create a new MachineType and SpareType. 否则EF认为您正在尝试创建新的MachineType和SpareType。 And because the Id field is set, the database won't allow the insert. 并且因为设置了Id字段,所以数据库将不允许插入。 Something like so: 像这样的东西:

newItem.MachineType = _context.MachineTypes.Find(<some_id>);
newItem.SpareType = _context.SpareTypes.Find(<some_id>);
context.SpareParts.Add(newItem);
context.SaveChanges();

Another thing you can do is expose the foreign key on your model, then it is enough to set it on the new instance before adding it to the DbSet. 您可以做的另一件事是在模型上公开外键,然后在将它添加到DbSet之前将其设置在新实例上就足够了。 In SparePart: 在SparePart中:

[ForeignKey("MachineType")]
public Int64 MachineTypeId { get; set; }

[ForeignKey("SpareType")]
public Int64 SpareTypeId{ get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF Core 无法为表中的标识列插入显式值 - EF Core Cannot insert explicit value for identity column in table 在 Sql 服务器中使用 BYTE 作为标识列类型时,EF 核心“无法为标识列插入显式值” - EF core "cannot insert explicit value for identity column" when using BYTE as identity column type in Sql Server EF核心:带有ValueGeneratedOnAdd的列拖曳“无法为标识列插入显式值…” - EF Core: Column with ValueGeneratedOnAdd trows “Cannot insert explicit value for identity column…” 使用 EF Core 插入 object 时“无法在表中插入标识列的显式值” - “Cannot insert explicit value for identity column in table” when inserting object with EF Core EF Core给我错误当IDENTITY_INSERT设置为OFF时,无法为表“标签”中的标识列插入显式值 - EF Core giving me error Cannot insert explicit value for identity column in table 'Tags' when IDENTITY_INSERT is set to OFF EF Core SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“MenuCategories”中插入标识列的显式值 - EF Core SqlException: Cannot insert explicit value for identity column in table 'MenuCategories' when IDENTITY_INSERT is set to OFF EF Core:当 IDENTITY_INSERT 在一对多上设置为 OFF 时,无法在表中插入标识列的显式值 - EF Core: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF on one to many Entity Framework Core:无法为表中的标识列插入显式值 - Entity Framework Core: Cannot insert explicit value for identity column in table IDENTITY_INSERT设置为OFF时,EF无法为表“ PATIENT DONOR”中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'PATIENT DONOR' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,EF无法为表&#39;X&#39;中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'X' when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM