2014-10-06 17 views
0

我想映射一個列表模型對象與它對父對象引用的子對象。 Json序列化會拋出「檢測到自檢參考循環」錯誤消息。我的模型類:自動映射器父子自引用循環

public class Event 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public ICollection<EventElement> EventElements { get; set; } 
    ... 
} 

public class EventElement 
{ 
    public int Id { get; set; } 
    ... 
    public int EventId { get; set; } 
    public virtual Event Event { get; set; } 
} 

我曾嘗試在Automapper配置中使用一些技巧。首先,拋出相同的錯誤: Mapper.CreateMap() .ForMember(vm => vm.EventElements,opt => opt.MapFrom(src => src.EventElements));

其次,爲列表中的每個對象返回null: Mapper.CreateMap()。MaxDepth(1);

我怎樣才能得到沒有循環的孩子的事件數據?

+0

你試圖忽略這個屬性,如[這裏]( http://stackoverflow.com/questions/4987872/ignore-mapping-one-property-with-automapper)? – Jonesopolis 2014-10-06 13:50:02

+0

可能重複的[JSON.NET錯誤自檢參考循環類型檢測](http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type) – 2014-10-06 13:50:49

+0

我想忽略孩子的Event屬性,我不知道如何。我知道在活動地圖中將源成員移除爲EventElements。我嘗試了本羅賓遜的建議,它適用於fiddler2,但我的SPA斷了。 – Daniel 2014-10-06 14:05:03

回答

1

您需要的DbContext禁用代理創建如下:

DbContext.Configuration.ProxyCreationEnabled = false; 

並使用「包括」 lambda表達式在你的倉庫

public IQueryable<Customer> GetAllCustomers() 
    { 
     return DbSet.AsQueryable().Include(s => s.StatusType).Include(s => s.CustomerCategory); 
    } 
+0

謝謝。前段時間我找到了同樣的解決方案,但我忘了這篇文章。當兩個EF類有一個虛擬屬性來鏈接它們之間的這些分類時,禁用自動代理創建是解決這個問題和其他循環引用問題的方法,但它強制手動包含所有要查詢的關係。 – Daniel 2016-02-01 15:26:41