实体框架核心放置操作不起作用

时间:2018-08-29 01:10:21

标签: c# entity-framework asp.net-web-api entity-framework-core

我得到

  

未处理的异常错误:实体类型“车辆”上的属性“ Id”是键的一部分,因此无法进行修改或将其标记为已修改。要使用标识的外键更改现有实体的主体,请先删除该依赖项,然后调用“ SaveChanges”,然后将该依赖项与新的主体相关联。实体类型“ Vehicle”的属性“ Id”是密钥的一部分,因此无法修改或标记为已修改。要使用标识的外键更改现有实体的委托人,请先删除依赖项,然后调用“ SaveChanges”,然后将依赖项与新委托人相关联

这是我的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 });
    }
}

Vehicle类:

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

1 个答案:

答案 0 :(得分:1)

免责声明:看起来好像您正在使用AutoMapper。因此,让我们看一下您的AutoMapper配置。具体来说,看看是否可以在其中找到类似.CreateMap<Vehicle, SaveVehicleResource>的东西。

这两种情况之一正在发生:

  1. 您的AutoMapper配置为针对这些类显式CreateMap,并且包含类似于.ForMember(x => x.Id, x.MapFrom(y => y.Id))的语句
  2. 您的AutoMapper未明确配置 ,这意味着它正在查找属性.Id,因为两个类都使用相同的名称对其进行了定义。您必须明确忽略该成员。

无论发生了哪些事情,您都必须告诉AutoMapper忽略该属性。

CreateMap<Vehicle, SaveVehicleResource>(...)
    .ForMember(x => x.Id, y => y.Ignore());