简体   繁体   English

将DTO映射到Entity AutoMapper时如何解决创建循环依赖关系

[英]How to fix when mapping DTO to Entity AutoMapper creates circular dependency

I have a database hierarchy like: Between Worksheet and Device is a one-to-one relationship. 我有一个数据库层次结构,如:在工作表和设备之间是一对一的关系。 When I'm trying to map the WorksheetDto to Worksheet AutoMapper makes a circular dependency through Worksheet and Device. 当我尝试将WorksheetDto映射到Worksheet时,AutoMapper通过Worksheet和Device进行循环依赖。

I've searched a lot after solution and I've found, that I have to ignore the Device's Worksheet reference. 解决方案后,我进行了大量搜索,发现必须忽略设备的工作表参考。 (I mean Device.Worksheet) (我的意思是Device.Worksheet)

Entities and DTOs: 实体和DTO:

public class Worksheet : EntityBase
    {
        public virtual Device Device { get; set; }
    }

public class WorksheetDto : EntityBaseDto
    {
        public virtual DeviceDto Device { get; set; }
    }

public class Device : EntityBase
    {
        public virtual Worksheet Worksheet { get; set; }
    }

public class DeviceDto : EntityBaseDto
    {
        public virtual WorksheetDto Worksheet { get; set; }
    }

AutoMapper config: AutoMapper配置:

var config = new MapperConfiguration(cfg =>
            {

                cfg.CreateMap<Device, DeviceDto>();
                    .ForMember(w => w.Worksheet, map => map.Ignore())
                    .PreserveReferences()
                    .ReverseMap();
            });

When I use it like this, nothing happens and got the following error: 当我像这样使用它时,什么也没有发生并出现以下错误:

System.InvalidOperationException: 'Multiplicity constraint violated. The role 'Worksheet_Device_Target' of the relationship 'RMDApp.DataLayer.Worksheet_Device' has multiplicity 1 or 0..1.'

So the summary is that I can see the circular dependency after all when I'm debugging. 因此,总结是,在调试时,我毕竟可以看到循环依赖关系。 So EF can't upload the Worksheet because of the error it provides. 因此EF由于提供的错误而无法上载工作表。

worksheet and device has one to one mapping , but choose whether you want to load device when you want to get worksheet or vice versa. 工作表和设备具有一对一的映射关系,但是选择要在获取工作表时是否要加载设备,反之亦然。

keep virtual only in one place, it will not try to load and will not create circular dependencies 将虚拟机仅保留在一个位置,它将不会尝试加载,也不会创建循环依赖项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM