New*_*ewm 6 automapper automapper-collections-ef-core ef-core-3.0
鉴于我有 2 个类,Foo 和 Bar:
public class Foo
{
private readonly List<Bar> _bars = new List<Bar>();
public int Id { get; private set; }
public string Name { get; private set; }
public IEnumerable<Bar> Bars => _bars;
public void AddBar(Bar bar)
{
_bars.Add(bar);
}
public static Foo Create(string name)
{
return new Foo { Name = name };
}
private Foo() { }
}
public class Bar
{
public int Id { get; private set; }
public string Description { get; private set; }
public static Bar Create(string description)
{
return new Bar { Description = description };
}
}
Run Code Online (Sandbox Code Playgroud)
有 2 个相应的 DTO,
public class BarDto
{
public int Id { get; set; }
public string Description { get; set; }
}
public class FooDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<BarDto> Bars { get; set; }
public FooDto()
{
Bars = new List<BarDto>();
}
}
Run Code Online (Sandbox Code Playgroud)
和 AutoMapper/AutoMapper.Collection.EntityFrameworkCore 设置
var config = new MapperConfiguration(cfg =>
{
cfg.AddCollectionMappers();
cfg.UseEntityFrameworkCoreModel<DemoContext>();
cfg.CreateMap<BarDto, Bar>().EqualityComparison((src, dest) => src.Id == dest.Id);
cfg.CreateMap<FooDto, Foo>().ForMember(dest => dest.Bars, opt =>
{
opt.MapFrom(s => s.Bars);
opt.UseDestinationValue();
}).EqualityComparison((src, dest) => src.Id == dest.Id);
});
Run Code Online (Sandbox Code Playgroud)
我有一个用例,其中传入的 FooDto 可能包含 Bars 集合中的插入、附加、更新和删除的项目,我试图通过以下方式处理:
但是,以下代码会产生一个InvalidOperationException异常,指出“无法跟踪实体类型 'Bar' 的实例,因为已跟踪具有键值 '{Id: 1}' 的另一个实例。附加现有实体时,请确保只有一个实体附加具有给定键值的实例“
var fooToUpdate = db.Foos.Include(_ => _.Bars).FirstOrDefault(_ => _.Id == fooDto.Id);
mapper.Map(fooDto, fooToUpdate);
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
我的理解是因为我正在EqualityComparison为BarDto -> Bar映射设置它应该更新被跟踪的实体并且保存操作应该成功因为它引用了同一个对象?
我不确定我是否以错误的方式解决这个问题,或者只是在配置中遗漏了一些东西。
更新
看来我面临的问题可能与github上的这个问题有关。
| 归档时间: |
|
| 查看次数: |
1334 次 |
| 最近记录: |