相关疑难解决方法(0)

使用Automapper更新现有的实体POCO

我使用EF4 DbContext为ASP.NET MVC应用程序提供模型.我使用ViewModels为视图和Automapper提供数据,以执行EF POCO和ViewModel之间的映射.Automapper做得很好,但在将ViewModel发回控制器进行更新后,我不清楚使用它的最佳方法.

我的想法是使用ViewModel中包含的密钥获取POCO对象.然后,我想使用Automapper使用ViewModel中的数据更新POCO:

[HttpPost]
public ActionResult Edit(PatientView viewModel)
{
    Patient patient = db.Patients.Find(viewModel.Id); 
    patient = Mapper.Map<ViewModel, Patient>(viewModel, patient);
    ...
    db.SaveChanges();
    return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. Find()方法返回一个代理而不是一个导致Automapper投诉的POCO.我如何获得POCO而不是代理?
  2. 这是执行更新的最佳做法吗?

asp.net-mvc viewmodel automapper entity-framework-4 dbcontext

17
推荐指数
1
解决办法
2万
查看次数

使用自定义解析程序跳过空值

我想使用automapper在我的公共数据协定和我的数据库模型之间进行映射.我创建了一个自动完成所有契约的类创建映射.我唯一的问题是,如果值不为null,我只想将合约中的值映射到数据库模型.我在这里看了其他问题但是看不到使用自定义解析器的示例.

这是我的一些代码

var mapToTarget = AutoMapper.Mapper.CreateMap(contract, mappedTo);
foreach (var property in contract.GetProperties().Where(property => property.CustomAttributes.Any(a => a.AttributeType == typeof(MapsToProperty))))
{
  var attribute = property.GetCustomAttributes(typeof(MapsToProperty), true).FirstOrDefault() as MapsToProperty;

  if (attribute == null) continue;

  mapToTarget.ForMember(attribute.MappedToName,
                    opt => 
                        opt.ResolveUsing<ContractToSourceResolver>()
                            .ConstructedBy(() => new ContractToSourceResolver(new MapsToProperty(property.Name, attribute.SourceToContractMethod, attribute.ContractToSourceMethod))));
}


private class ContractToSourceResolver : ValueResolver<IDataContract, object>
{
  private MapsToProperty Property { get; set; }

  public ContractToSourceResolver(MapsToProperty property)
  {
     Property = property;
  }

  protected override object ResolveCore(IDataContract contract)
  {
     object result = null;
     if (Property.ContractToSourceMethod != null)
     { …
Run Code Online (Sandbox Code Playgroud)

c# automapper

15
推荐指数
3
解决办法
2万
查看次数