使用中的异常Automapper:无法跟踪实体类型的实例,因为已经跟踪了具有该键的另一个实例

时间:2018-06-08 14:34:47

标签: asp.net-core entity-framework-core automapper

我将ASP.NET Core与EFCore 2.0.3和Automapper 6.2.2一起使用

这是我的模特:

    public class StudentClass
    {
        public int Id { get; set; }
        public int ClassId { get; set; }
        public Class Class { get; set; }
        public int ProfId { get; set; }
        public Professor Prof { get; set; }
        public string Description { get; set; }
        public DateTimeOffset LastUpdateTime { get; set; }
        public DateTimeOffset CreateTime { get; set; }
    }

和我的实体

    public class StudentClassEntity
    {
        public int Id { get; set; }

        public int ClassId { get; set; }
        [ForeignKey("ClassId")]
        public virtual Class Class { get; set; }
        public int ProfId { get; set; }
        [ForeignKey("ProfId")]
        public Professor Prof { get; set; }
        public string Description { get; set; }
        public DateTimeOffset LastUpdateTime { get; set; }
        public DateTimeOffset CreateTime { get; set; }
        public virtual List<Task> Tasks { get; set; }
    }

我尝试更新StudentClass所以这是我的示例方法:

        public void Update()
        {

            var studentclass = new StudentClass();
            studentclass.Id = 7;
            studentclass.CreateTime = System.DateTimeOffset.MinValue;
            studentclass.Description = $"new desc - {System.DateTime.Now.Millisecond}";
            studentclass.ProfId = 5;
            studentclass.ClassId = 7;


            var entity = _context.StudentClasses.FirstOrDefault(x => x.Id == studentclass.Id);

            if (entity != null)
            {
                entity = _mapper.Map<StudentClassEntity>(studentclass);
                _context.StudentClasses.Update(entity);
                _context.SaveChanges();
            }
        }

我的Automapper地图:

 CreateMap<StudentClass, StudentClassEntity>()
 .ForMember(m => m.Description, o => o.MapFrom(x => x.Description))
 .ForMember(m => m.LastUpdateTime, o => o.MapFrom(f => DateTimeOffset.Now))
 .ForAllOtherMembers(m => m.UseDestinationValue());

所以我得到了例外:

The instance of entity type cannot be tracked because another instance with the key value "Id:7" is already being tracked.

但如果不使用Automapper,我只需手动映射:

if (entity != null)
{
     //entity = _mapper.Map<StudentClassEntity>(studentclass);
    entity.Description = studentclass.Description;
    entity.LastUpdateTime = DateTimeOffset.Now;

    _context.StudentClasses.Update(entity);
    _context.SaveChanges();
}

它会毫无例外地更新数据库。问题出在哪儿?我错过了什么吗?如何在Automapper中创建Map以毫无例外地更新实体?

1 个答案:

答案 0 :(得分:1)

我发现如果我使用

entity = _mapper.Map<StudentClassEntity>(studentclass);

Automapper将为实体创建新对象,显然它与上下文中的引用不同。但是,如果我使用

_mapper.Map(studentclass, entity);

Automapper不会创建新实例,实体与上下文中的引用相同。