2017-07-25 74 views
1

我有插入數據到具有外鍵的數據庫表的問題。 由於錯誤我得到EF核心插入標識列的顯式值

不能用於標識列在表中插入顯式值 「MachineTypes」當IDENTITY_INSERT設置爲OFF.Cannot插入用於標識列 明確的價值「SpareTypes」當 IDENTITY_INSERT爲設置爲OFF。

BaseEntity.cs

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

    public DateTime CreateDate { get; set; } 
} 

MachineType.cs

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

SpareType.cs

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

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

張貼

[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

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"]); 
     } 
    } 

在發佈的所有數據

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

控制器是捕捉正確的,但什麼時候應該進入進入數據庫我得到一個錯誤。 enter image description here

回答

3

當插入新的SparePart實例時,需要事先從相同的DbContext獲取MachineType和SpareType引用。否則EF認爲您正在嘗試創建新的MachineType和SpareType。而且由於Id字段已設置,數據庫將不允許插入。事情是這樣:

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

你能做的就是暴露你的模型外鍵的另一件事,那麼它是足夠將它添加到DbSet之前設置它的新實例。在備件中:

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

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

非常感謝。經過深入而長期的調查,我也發現了這一點。 –