0
我目前正在尋找一種方法來「過濾」一個對象,然後將其發送到我的存儲庫;也就是說,根據上下文,保留原始實例的某些屬性,同時忽略或替換具有默認值的其他屬性。事實上,我相信這可能是一種取代所有我的DTO的方式,在不需要進行類型轉換的情況下,同時保護我的應用程序免於「過量發佈」,如Brad Wilson's blog中所述。
換句話說,我想要做的是更換:(!不工作,當然)
public class UserRegistrationModel {
public string FirstName { get; set; }
public string Gender { get; set; }
public string LastName { get; set; }
}
public class UserGenderEditModel {
public string Gender { get; set; }
}
public class User {
public string FirstName { get; set; }
public string Gender { get; set; }
public bool IsVIP { get; set; }
public string LastName { get; set; }
}
class Program {
static void Main(string[] args) {
Mapper.CreateMap<UserRegistrationModel, User>()
.ForMember(d => d.FirstName, o => o.MapFrom(s => s.FirstName))
.ForMember(d => d.Gender, o => o.MapFrom(s => s.Gender))
.ForMember(d => d.IsVIP, o => o.UseValue(false))
.ForMember(d => d.LastName, o => o.MapFrom(s => s.LastName));
Mapper.CreateMap<UserGenderEditModel, User>()
.ForMember(d => d.FirstName, o => o.Ignore())
.ForMember(d => d.Gender, o => o.MapFrom(s => s.Gender))
.ForMember(d => d.IsVIP, o => o.Ignore())
.ForMember(d => d.LastName, o => o.Ignore());
var user = Mapper.Map<UserRegistrationModel, User>(new UserRegistrationModel {
// filling properties
});
}
}
像這樣的東西:
public class User {
public string FirstName { get; set; }
public string Gender { get; set; }
public bool IsVIP { get; set; }
public string LastName { get; set; }
}
class Program {
static void Main(string[] args) {
Mapper.CreateMap<User, User>()
.ForMember(d => d.FirstName, o => o.MapFrom(s => s.FirstName))
.ForMember(d => d.Gender, o => o.MapFrom(s => s.Gender))
.ForMember(d => d.IsVIP, o => o.UseValue(false))
.ForMember(d => d.LastName, o => o.MapFrom(s => s.LastName))
.ForContext("UserRegistration"); // not real.
Mapper.CreateMap<User, User>()
.ForMember(d => d.FirstName, o => o.Ignore())
.ForMember(d => d.Gender, o => o.MapFrom(s => s.Gender))
.ForMember(d => d.IsVIP, o => o.Ignore())
.ForMember(d => d.LastName, o => o.Ignore());
.ForContext("UserGenderEdition"); // not real.
var user = Mapper.Map<User, User>(new User {
// filling properties
}, "UserRegistration"); // not real.
}
}
那麼,有沒有一種方法實現這個工作(不一定使用AutoMapper)?
儘管如此,我並不是在尋找與MVC模型綁定機制直接相關的內容,因爲我希望在web服務或控制檯應用程序中重用該機制。
謝謝!