Dot-Net

如何刪除實體框架中的循環引用?

  • June 6, 2019

我的 Customer 和 Order 實體之間的循環引用導致序列化期間出現異常。有什麼方法可以強制 EF 在這兩個實體之間生成單向引用?提前致謝!

當我需要序列化時,我通常會投影到其他類型上。這消除了循環引用,以及我不想序列化的其他數據。例如:

var q = (from c in Repository.Customers()
        where c.Id == id
        select new 
        {
            Name = c.Name,
            Orders = from o in C.Orders
                     select new
                     {
                         Date = o.Date
                     }
        }).First();
return Json(q);

我已經在 EF 3.5 中解決了這個問題,方法是將 Child 的導航屬性 Getter 從 public 更改為 Internal。

引用自:https://stackoverflow.com/questions/2107535