我得到
未处理的异常错误:实体类型车辆"上的属性"Id"是键的一部分,因此无法进行修改或将其标记为已修改.要使用标识的外键更改现有实体的主体,请先删除该依赖项,然后调用"SaveChanges",然后将该依赖项与新的主体相关联.实体类型"Vehicle"的属性"Id"是密钥的一部分,因此无法进行修改或标记为已修改.要使用标识的外键更改现有实体的委托人,请先删除依赖项,然后调用"SaveChanges",然后将依赖项与新委托人关联起来.
Unhandled Exception Error: the property 'Id' on entity type 'Vehicle' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principalThe property 'Id' on entity type 'Vehicle' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal
这是我的Put API:
Here is my Put API:
[HttpPut("{id}")] public IActionResult UpdateVehicle(int id, [FromBody] SaveVehicleResource vehicleResource) { if (!ModelState.IsValid) return BadRequest(ModelState); var vehicle = context.Vehicles.Include(v => v.Features).SingleOrDefault(v => v.Id == id); if (vehicle == null) return NotFound(); mapper.Map(vehicleResource, vehicle); vehicle.LastUpdate = DateTime.Now; context.SaveChanges(); var result = mapper.Map<Vehicle, SaveVehicleResource>(vehicle); return Ok(result); }这里是 DbContext :
public class VegaDbContext : DbContext { public DbSet<Make> Makes { get; set; } public DbSet<Feature> Features { get; set; } public DbSet<Vehicle> Vehicles { get; set; } public DbSet<Model> Models { get; set; } public VegaDbContext(DbContextOptions<VegaDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<VehicleFeature>().HasKey(vf => new { vf.VehicleId, vf.FeatureId }); } }车辆类:
public class Vehicle { public int Id { get; set; } public int ModelId { get; set; } public Model Model { get; set; } public bool IsRegistered { get; set; } public Contact Contact { get; set; } public ICollection<VehicleFeature> Features { get; set; } public DateTime LastUpdate { get; set; } public Vehicle() { Features = new Collection<VehicleFeature>(); } }VehicleFeature 类:
public class VehicleFeature { public int VehicleId { get; set; } public int FeatureId { get; set; } public Vehicle Vehicle { get; set; } public Feature Feature { get; set; } } 推荐答案免责声明:看起来好像您正在使用AutoMapper.因此,让我们看一下您的AutoMapper配置.具体来说,看看是否可以在其中找到类似 .CreateMap< Vehicle,SaveVehicleResource> 的东西.
Disclaimer: it really looks like you're using AutoMapper. So let's take a look at your AutoMapper configuration. Specifically, see if you can find something like .CreateMap<Vehicle, SaveVehicleResource> in there.
这两种情况之一正在发生:
无论发生了哪些事情,您都必须告诉AutoMapper忽略该属性.
Regardless which of those things has happened, you'll have to tell AutoMapper to ignore that property.
CreateMap<Vehicle, SaveVehicleResource>(...) .ForMember(x => x.Id, y => y.Ignore());更多推荐
实体框架核心放置操作不起作用
发布评论