在MVC项目中,我使用Autommaper链接ViewModel和Entities(EF6)。我正在寻找自动化,所以我正在尝试使用Automapper管理DBContext。但是,似乎上下文松了他的变化。你知道为什么pContext在两个断点之间松动了吗?
断点1:pContext.ChangeTracker.HasChanges()= true
断点2:pContext.ChangeTracker.HasChanges()= false
public void SaveAddress(AddressViewModel pModel)
{
OpenTransaction();
CreateMapAddressModel(Context);
var lAddress = Mapper.Map<AddressViewModel, Address>(pModel);
//new DataProvider<Address>(Context).Insert(lAddress);
CloseTransaction();
}
public void CreateMapAddressModel(MyModel pContext)
{
if (Mapper.FindTypeMapFor(typeof(AddressViewModel), typeof(Address)).IsNull())
{
Mapper.CreateMap<AddressViewModel, Address>().IgnoreAllNonExisting()
.ConstructUsing((AddressViewModel s) => pContext.Set<Address>().Find(s.Id) ?? pContext.Set<Address>().Create())
.AfterMap((src, dest) => dest.ApplicationUser = pContext.Set<ApplicationUser>().FirstOrDefault(x => x.Id == src.ApplicationUserId))
.AfterMap((src, dest) => pContext.Entry(dest).State = dest.Id == Guid.Empty ? EntityState.Added : EntityState.Modified)
.AfterMap((src, dest) =>
{
if (dest.Id == Guid.Empty)
{
//pContext.Set<Address>().Add(dest);
System.Diagnostics.Debug.WriteLine(pContext.Entry(dest).State);//Value = Added
System.Diagnostics.Debug.WriteLine(pContext.ChangeTracker.HasChanges());//Value = True//<-- Breakpoint 1
}
})
;
}
}//<-- Breakpoint 2