Sto provando Entity Framework Code prima CTP4. Supponiamo di avere:Il programma di automapper può mappare una chiave esterna a un oggetto utilizzando un repository?
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>();
La mappatura al modello Modifica non è un problema. Sul mio schermo seleziono madre attraverso un certo controllo (DropDownList, autocompletamento, ecc) e l'Es della madre viene scritto sul retro:
[HttpPost]
public ActionResult Edit(ChildEdit posted)
{
var repo = new TestContext();
var mapped = Mapper.Map<ChildEdit, Child>(posted); // <------- ???????
}
Come devo risolvere l'ultima mappatura? Non voglio mettere Mother_Id nell'oggetto Child. Per ora uso questa soluzione, ma spero che possa essere risolta con 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);
EDIT questo funziona, ma ora devo farlo per ogni chiave esterna (BTW: contesto sarebbe iniettato soluzione finale):
Mapper.CreateMap<ChildEdit, Child>();
.ForMember(i => i.Mother,
opt => opt.MapFrom(o =>
new TestContext().Parents.Find(o.MotherId)
)
);
Quello che mi piacerebbe molto sarebbe:
Mapper.CreateMap<int, Parent>()
.ForMember(i => i,
opt => opt.MapFrom(o => new TestContext().Parents.Find(o))
);
Mapper.CreateMap<ChildEdit, Child>();
Ciò è possibile con Automapper?
Funziona come un incantesimo. Grazie. –
Puoi mostrare come usare la tua soluzione quando voglio mappare l'id all'entità? Voglio dire come mappare quando ho implementato tutto? – user2412672