我有一个我的产品的模型视图,它有许多属性,我想用实体框架将它保存在数据库中。但是简单的方法就是使用这段代码:
public void NewProduct(NewProductModel viewModel)
{
var dbModel = repository.FindProductById(viewModel.id);
dbModel.Model = viewModel.Model;
dbModel.Brand = viewModel.Brand;
dbModel.Cost = viewModel.Cost;
//its' too many
repository.AddProduct(dbModel);
repository.SaveChange();
}
但财产太多了。 你有更好的方法来减少这些代码吗?
答案 0 :(得分:0)
您可以使用AutoMapper或(https://github.com/AutoMapper/AutoMapper/wiki/Configuration)。
这是一个简短的例子:
// Make sure you check out the documentation before copy/pasting this
// code and using it as it's not the proper way of using automapper
public void NewProduct(NewProductModel viewModel)
{
var dbModel = repository.FindProductById(viewModel.id);
// If the properties have the same names already then AutoMapper can do it automatically
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<NewProductModel, YourDBModelType>());
// Otherwise you use can create your own mapping rules
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<NewProductModel, YourDBModelType>()
.ForMember(dest => dest.Model, opt => opt.MapFrom(src => src.Model))
.ForMember(dest => dest.Brand, opt => opt.MapFrom(src => src.Brand))
.ForMember(dest => dest.Cost, opt => opt.MapFrom(src => src.Cost)));
// mapping
var mapper = config.CreateMapper();
var dbModel = mapper.Map<YourDBModelType>(viewModel);
repository.AddProduct(dbModel);
repository.SaveChange();
}
您可以在github repo
的文档部分找到更多信息