[英]AutoMapper Merge Two Types Ignoring one property
I have this entity: 我有这个实体:
public class MyType
{
public Guid Id {get;set;}
public string Name {get;set;}
}
I want to merge two of these types together, but the source Id
needs to be unchanged. 我想将这两种类型合并在一起,但源
Id
必须保持不变。
So the objects are filled as such: 因此,对象按如下方式填充:
From the Database => MyType {
Id: 012312-42134-12321-12,
Name: "This Type"
}
From the View => MySecondType {
Id: null,
Name: "This Type Changed"
}
And I want to merge MySecondType
into MyType
but ignore the Id
field in the merge. 我想将
MySecondType
合并到MyType
但忽略合并中的Id
字段。
So I thought maybe doing: 所以我想也许正在做:
Mapper.Map(mySecondType, myType);
To get the database myType
to be filled with the view mySecondType
but there is not setting to ignore a property. 若要获取数据库
myType
来填充视图mySecondType
但没有设置忽略的属性。
When setting up your AutoMapper you could ignore a property: 设置AutoMapper时,可以忽略属性:
Mapper
.CreateMap<MySecondType, MyType>()
.ForMember(x => x.Id, opt => opt.Ignore());
This being said, it would make far more sense to use a view model in ASP.NET MVC. 话虽这么说,在ASP.NET MVC中使用视图模型会更有意义。 So you would have your DB bound model
MyType
with Id
and Name
properties and have a MyTypeViewModel
which will only have a Name
property and be used in your view. 因此,您将拥有具有
Id
和Name
属性的数据库绑定模型MyType
,并具有MyTypeViewModel
,该MyTypeViewModel
仅具有Name
属性并在视图中使用。 Then you don't need to be ignoring any properties. 然后,您无需忽略任何属性。 This will automatically come from the design of your view models.
这将自动来自您的视图模型的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.