AutoMapper更新嵌套集合

时间:2019-06-26 09:52:36

标签: c# entity-framework automapper ef-core-2.0

我正在使用AutoMapper来更新我的类嵌套集合以及其他属性,但这会引发以下异常,

Cannot insert explicit value for identity column in table 'tblEmpLanguages' when IDENTITY_INSERT is set to OFF.

我正在使用Swagger来测试API。

班级

public class Test : BasicEntity
    {
        public Test()
        {
            this.Languages = new List<Language>();
        }

        public string Name { get; set; }
        public List<Language> Languages { get; set; }

    }

基本实体:

  public class BasicEntity: IEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public DateTime CreatedDate { get; set; } = DateTime.Now;
        public int CreatedBy { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime? ModifiedDate { get; set; } = DateTime.Now;
        public int ModifiedBy { get; set; }
        public bool Active { get; set; } = true;

    }

映射器:

CreateMap<Test, Test>()
          .ForMember(dest => dest.Languages, opt => opt.MapFrom(src => src.Languages));

控制器(更新代码):

 var dest = _mapper.Map(source, dest);
    _repo.Tests.UpdateTest(dest);
    _repo.Save(); // Exception thrown here

大刀阔斧的更新:

{
  "Id": 1,
  "CreatedDate": "2019-06-26T09:46:51.563Z",
  "CreatedBy": 0,
  "ModifiedDate": "2019-06-26T09:46:51.563Z",
  "ModifiedBy": 0,
  "Active": true,
  "Name": "ABC",
  "Languages": [
    {
      "Id": 1,
      "CreatedDate": "2019-06-26T09:46:51.563Z",
      "CreatedBy": 0,
      "ModifiedDate": "2019-06-26T09:46:51.563Z",
      "ModifiedBy": 0,
      "Active": true,
      "EmpId": 0,
      "LanguageId": 0,
      "Mothertongue": true
    }
  ]
}

我尝试更新名称属性和语言列表。我在哪里错了,我应该在这里改变什么?

0 个答案:

没有答案