我正在尝试使用Entity Framework Code First CTP4。假设我有:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public Parent Mother { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
public class ChildEdit
{
public int Id { get; set; }
public string Name { get; set; }
public int MotherId { get; set; }
}
Mapper.CreateMap<Child, ChildEdit>();
将数据映射到编辑模型并不是问题。在我的屏幕上,我通过某些控件(下拉列表、自动完成器等)选择母亲,并将母亲的ID提交回后端:
[HttpPost]
public ActionResult Edit(ChildEdit posted)
{
var repo = new TestContext();
var mapped = Mapper.Map<ChildEdit, Child>(posted); // <------- ???????
}
我应该如何解决最后一个映射?我不想在Child对象中放置Mother_Id。目前我使用这个解决方案,但我希望可以在Automapper中解决。
我该如何解决最后一个映射?我不想将 Mother_Id 放入 Child 对象中。目前我使用这种解决方案,但我希望能在 Automapper 中解决。
Mapper.CreateMap<ChildEdit, Child>()
.ForMember(i => i.Mother, opt => opt.Ignore());
var mapped = Mapper.Map<ChildEdit, Child>(posted);
mapped.Mother = repo.Parents.Find(posted.MotherId);
编辑 这个方法是有效的,但现在我必须为每个外键都执行这个操作(顺便说一句:上下文将在最终解决方案中注入):
Mapper.CreateMap<ChildEdit, Child>();
.ForMember(i => i.Mother,
opt => opt.MapFrom(o =>
new TestContext().Parents.Find(o.MotherId)
)
);
我真正想要的是:
Mapper.CreateMap<int, Parent>()
.ForMember(i => i,
opt => opt.MapFrom(o => new TestContext().Parents.Find(o))
);
Mapper.CreateMap<ChildEdit, Child>();
使用Automapper可以实现这个吗?