循环引用导致堆栈溢出与Automapper [英] Circular reference causing stack overflow with Automapper

查看:594
本文介绍了循环引用导致堆栈溢出与Automapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Automapper我NHibernate的代理对象(DTO)映射到我的CSLA业务对象

I'm using Automapper to map my NHibernate proxy objects (DTO) to my CSLA business objects

我使用功能NHibernate创建的映射 - 这是做工精细

I'm using Fluent NHibernate to create the mappings - this is working fine

我的问题是,订单 OrderLines <集合/ code>,每一个都有到订单的参考。

The problem I have is that the Order has a collection of OrderLines and each of these has a reference to Order.

public class OrderMapping : ClassMap<OrderDTO>
{
    public OrderMapping()
    {
        // Standard properties
        Id(x => x.OrderId);
        Map(x => x.OrderDate);
        Map(x => x.Address);

        HasMany<OrderLineDTO>(x => x.OrderLines).KeyColumn("OrderId").Inverse();

        Table("`Order`");
    }
}

public class OrderDTO
{
    // Standard properties
    public virtual int OrderId { get; set; }
    public virtual DateTime OrderDate { get; set; }
    public virtual string Address { get; set; }

    // Child collection properties
    public virtual IList<OrderLineDTO> OrderLines { get; set; } <-- this refs the lines
}

public class OrderLineMapping : ClassMap<OrderLineDTO>
{
    public OrderLineMapping()
    {
        // Standard properties
        Id(x => x.OrderLineId);
        References<OrderDTO>(x => x.Order).Column("OrderId");
        Map(x => x.Description);
        Map(x => x.Amount);

        Table("`OrderLine`");
    }
}

public class OrderLineDTO
{
    // Standard properties
    public virtual int OrderLineId { get; set; }
    public virtual string Description { get; set; }
    public virtual decimal Amount { get; set; }

    public virtual OrderDTO Order { get; set; } // <-- this refs the order
}



这些DTO对象映射到订单 OrderLines CSLA对象分别为

These DTO objects map to Order and OrderLines CSLA objects respectively

当自动映射 OrderLines A OrderLinesDTO 列表映射。然后自动映射器映射订单就行属性,它映射回订单,然后循环地图回订单行,然后订单

When auto-mapping to OrderLines a list of OrderLinesDTO is mapped. Auto mapper is then mapping the "Order" property on of the lines, which maps back to Order which then circularly maps back to OrderLine, then to Order and so on

有谁知道,如果Automapper可以避免这个循环引用

Does anyone know if Automapper can avoid this circular reference?

推荐答案

在您A​​utomapper配置:

In your Automapper configuration:

Mapper.Map<OrderLine, OrderLineDTO>()
    .ForMember(m => m.Order, opt => opt.Ignore());

Mapper.Map<Order, OrderDTO>()
    .AfterMap((src, dest) => { 
         foreach(var i in dest.OrderLines) 
             i.Order = dest;
         });

这篇关于循环引用导致堆栈溢出与Automapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆