I'm trying to update a model that is getted by automapper bind.
When my update function execute
Context.Entry(obj).State = EntityState.Modified;
entity framework throw this exception
Multiplicity constraint violated. The role 'LegislationCategory_Legislations_Source' of the relationship 'Creci.Infra.Data.Context.LegislationCategory_Legislations' has multiplicity 1 or 0..1.
If i try to update the model without use automapper it's works fine.
The relations is
public class LegislationCategoryMap : EntityTypeConfiguration<LegislationCategory>
{
public LegislationCategoryMap()
{
...
HasMany(x => x.Legislations)
.WithRequired(x => x.Category)
.WillCascadeOnDelete(true);
}
}
public class LegislationMap : EntityTypeConfiguration<Legislation>
{
public LegislationMap()
{
...
HasRequired(x => x.Category);
}
}
And my mapper profile configuration is
CreateMap<EditLegislationViewModel, Legislation>()
.EqualityComparision((vm, m) => vm.Id == m.Id)
.AfterMap((vm, m) =>
{
...
if (vm.Category == null && vm.CategoryId != 0)
{
m.Category = new LegislationCategoryRepository().GetById(vm.CategoryId);
}
});
I used aftermap to map category to Legislation object when viewmodel is binded from request.
my controller code is
var model = Mapper.Map(viewModel, repository.GetById(id));
repository.Update(model);
and the update function
public void Update(TEntity obj)
{
Validate(obj);
using (var transaction = Context.Database.BeginTransaction())
{
try
{
Context.Entry(obj).State = EntityState.Modified;
Context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}