如何解决执行存储库Update时违反多重约束
ASP.NET,C#,MVC5,EF6代码优先-使用Bogus Faker植入数据库。具有AutoMapper.Collections.EntityFramework和ASPNET Boilerplate的AutoMapper。此时,存储库是默认的。
我正在尝试往返-Get()
和Report
,然后将其发送到强类型的View
,然后将其发送回Controller
,然后将其保存到数据库。
问题是_repository.Update()
在一对一关系上引发了Multiplicity Constraint Violation
异常。错误:
“违反多重性约束。角色 关系的“ Inspection_PropertyAttributes_Target” 'BinnerValuations.EntityFramework.Inspection_PropertyAttributes'具有 多重性1或0..1。“
我怀疑此错误是由以下三种配置之一引起的:EF代码优先注释,AutoMapper映射配置或我在执行Update()
之前准备实体的方式。我不能肯定地说,但我怀疑问题是由我的AutoMapper映射配置引起的(或缺少它们)。
实体结构是Report
是主要实体,并且可以包含零个或多个Inspection
。每个Inspection
是与PropertyAttributes
一对一的主要对象。
Report 1
Inspection 0 or many per Report
PropertyAttributes 1 per Inspection (required)
报告实体:
public class Report : Entity<int>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override int Id { get; set; }
{ .... }
public virtual ICollection<Inspection> Inspections { get; set; }
}
每个报告的零次或多次检查:
public class Inspection : Entity<int>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override int Id { get; set; }
[ForeignKey("Report")]
public int ReportId { get; set; }
public virtual Report Report { get; set; }
{ .... }
[Required] public virtual PropertyAttributes PropertyAttributes { get; set; }
}
每次检查一个PropertyAttributes实体:
public class PropertyAttributes : Entity<int>
{
[Key]
[ForeignKey("Inspection")]
public override int Id { get; set; }
{ .... }
public virtual Inspection Inspection { get; set; }
}
实体模型和DTO可以很好地读取数据。我的强类型视图全部按预期工作。从View传递到Controller的模型在前端和后端进行验证。
示例Get()
var id = 9;
Report report = _reportRepository.Get(id);
report
已完全填充-所有一对多和一对一对象都填充了正确的数据。
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(ReportViewModel model)
{
if (!ModelState.IsValid) { ... }
else
{
// Map View to DTO
var reportDto = _objectMapper.Map<ReportDto>(model);
// Entity original
var report = _reportsRepository.Get(reportDto.Id);
// Merge form values with real entity
var updatedReport = _objectMapper.Map(reportDto,report);
try
{
// Update entity
_reportsRepository.Update(updatedReport); <<-- Throws InvalidOperationException
}
catch (InvalidOperationException e)
{
}
catch (Exception e)
{
}
}
}
AutoMapper配置:
CreateMap<Report,ReportDto>();
CreateMap<ReportDto,Report>();
CreateMap<Inspection,InspectionDto>();
CreateMap<InspectionDto,Inspection>();
CreateMap<PropertyAttributes,PropertyAttributesDto>();
CreateMap<PropertyAttributesDto,PropertyAttributes>();
至于我上面的代码...我已经尝试了使用数据注释的许多不同的EF Code First配置。在某一时刻,异常消息说Inspection_PropertyAttributes
_Source ,但现在说的是Inspection_PropertyAttributes
_Target 。
我用尽了所有可以想到的选项,输入的每个Google搜索都显示了我已经访问过的结果(至少一次!)。
有人知道为什么会这样吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。