C# 自动映射:更新现有集合
使用此方法映射现有实体相当简单C# 自动映射:更新现有集合,c#,automapper,C#,Automapper,使用此方法映射现有实体相当简单 Mapper.Map<Source, Destination>(source, destination); Mapper.Map(源、目标); 但我想更新现有的集合,如: var class1List = new List<Class1> { new Class1 { Id = 1, Name = "Name1", Text = "Text1"
Mapper.Map<Source, Destination>(source, destination);
Mapper.Map(源、目标);
但我想更新现有的集合,如:
var class1List = new List<Class1>
{
new Class1 { Id = 1, Name = "Name1", Text = "Text1"},
new Class1 { Id = 2, Name = "Name2", Text = "Text2"},
new Class1 { Id = 3, Name = "Name3", Text = "Text3" },
};
var class2List = new List<Class2>
{
new Class2 { Id = 1, Name = "a" },
new Class2 { Id = 2, Name = "b" },
};
ObjectMapper.Map<List<Class1>, List<Class2>>(class1List, class2List)
.Key("Id"); //here I'd supposedly specify a key to map the objects but there is no such a method
/*
the desired result is an updated collection with one new item:
class2List = new List<Class2>
{
new Class2 { Id = 1, Name = "Name1", Text = "Text1"}, //this is updated by Id
new Class2 { Id = 2, Name = "Name2", Text = "Text2"}, //this is updated by Id
new Class2 { Id = 3, Name = "Name3", Text = "Text3" }, //this is a new object because there were no matching Id in the list
}
*/
var classalist=新列表
{
新类别1{Id=1,Name=“Name1”,Text=“Text1”},
新类别1{Id=2,Name=“Name2”,Text=“Text2”},
新类别1{Id=3,Name=“Name3”,Text=“Text3”},
};
var class2List=新列表
{
新类2{Id=1,Name=“a”},
新类2{Id=2,Name=“b”},
};
ObjectMapper.Map(ClassList,class2List)
.Key(“Id”)//这里我应该指定一个键来映射对象,但是没有这样的方法
/*
所需的结果是更新集合,其中包含一个新项:
class2List=新列表
{
新类2{Id=1,Name=“Name1”,Text=“Text1”},//这是由Id更新的
新的Class2{Id=2,Name=“Name2”,Text=“Text2”},//这是由Id更新的
new Class2{Id=3,Name=“Name3”,Text=“Text3”},//这是一个新对象,因为列表中没有匹配的Id
}
*/
有可能通过AutoMapper实现这一点吗?
因为没有指定要映射的键,它实际上只返回3个新的Class2项的集合,这些项与初始集合无关。来自注释:
对于automapper集合,意味着您可以在其他地方配置ID等效性,例如
mapperconfig.CreateMap<Class1, Class2>().EqualityComparison((c1, c2) => c1.Id == c2.Id);
mapperconfig.CreateMap().EqualityComparison((c1,c2)=>c1.Id==c2.Id);
然后你可以把一个1类的集合映射到一个2类的集合@CaiusJard是的,这正是我需要的。如果你把它写成一个完整的答案,我可以把它标记为接受。