简体   繁体   中英

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.

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.

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.

When setting up your AutoMapper you could ignore a property:

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. 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. Then you don't need to be ignoring any properties. This will automatically come from the design of your view models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM