gpt4 book ai didi

c# - EF Core 为标识列插入显式值

转载 作者:行者123 更新时间:2023-11-30 14:23:26 25 4
gpt4 key购买 nike

我在向具有外键的数据库表中插入数据时遇到问题。作为错误,我得到了

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.

基础实体.cs

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

public DateTime CreateDate { get; set; }
}

机器类型.cs

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

备用类型.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

 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

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

在发布过程中,所有数据都被正确捕获,但是当应该插入数据库时​​我遇到了错误。 enter image description here

最佳答案

插入新的 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; }

关于c# - EF Core 为标识列插入显式值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com