問題描述
- 我創建了一個數據庫,因為我有多個表之間存在關系.
- 嘗試從我的 WEB 應用程序獲取數據時出現此錯誤<塊引用>
"'檢測到類型為 'System.Data.Entity.DynamicProxies.PrescriptionMaster_2C4C63F6E22DFF8E29DCAC8D06EBAE038831B58747056064834E80E41B5C4E4A'的自引用循環.PathMaster'[pPrescription]
- 我不明白為什么我會收到這個錯誤,當我刪除表之間的關系時,我從中獲得了正確的數據.
我嘗試了其他解決方案,例如添加
"config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling= Newtonsoft.Json.ReferenceLoopHandling.Ignore;"
在 Webconfig.cs 中,但對我沒有任何作用.
請幫幫我,我該怎么辦?
防止這種情況發生的唯一正確方法是不發送實體框架對象(可能包含此類循環)進入 JSON 序列化器(不太擅長知道何時停止序列化).
相反,創建模擬前端實際需要的 EF 對象部分的 ViewModel,然后使用 EF 對象填充這些 ViewModel.
一種快速而骯臟的方法是只使用匿名對象,例如:
返回新的{產品 = 新{Id = EF_Product.Id,名稱 = EF_Product.Name}};
一個好的經驗法則是僅將 EF 對象中的簡單屬性(數字、布爾值、字符串、日期時間)分配給 ViewModel 項.一旦遇到作為另一個 EF 對象(或 EF 對象的集合)的 EF 對象屬性,那么您也需要將它們轉換為未鏈接到 EF 的簡單"對象.
另一方面,還有諸如 AutoMapper 之類的庫.如果您決定需要實際的 ViewModel 類,那么 AutoMapper 將幫助以非常結構化的方式將 EF 對象映射到這些 ViewModel.
- I Have Create a DB in that I am Having Multiple tables having Relationship between them.
- When a try to get data from my WEb app i get this error
"'Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PrescriptionMaster_2C4C63F6E22DFF8E29DCAC8D06EBAE038831B58747056064834E80E41B5C4E4A'. Path '[0].Patient.PrescriptionMasters"
- I coudn't get why i am getting this error, and when i remove the relationships between tables i get proper data From it.
I have Tried other solutions like adding
"config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; "
in Webconfig.cs but nothing has worked for me.
Please help me, what should I do ?
The only proper way to prevent this from happening is by not sending Entity Framework objects (which may contain such loops) into the JSON Serializer (which is not too good at knowing when to stop serializing).
Instead, create ViewModels that mimic the parts of the EF Objects that your Front End actually needs, then fill those ViewModels using the EF Objects.
A quick-and-dirty way is to just use anonymous objects, for example:
return new
{
Product = new
{
Id = EF_Product.Id,
Name = EF_Product.Name
}
};
A good rule-of-thumb is to only assign simple properties (number, bool, string, datetime) from the EF Objects to the ViewModel items. As soon as you encounter an EF Object property that is yet another EF Object (or a collection of EF Objects), then you need to translate those as well to 'simple' objects that are not linked to EF.
On the other end of the spectrum there are libraries such as AutoMapper. If you decide that you need actual ViewModel classes, then AutoMapper will help mapping the EF Objects to those ViewModels in a very structured way.
這篇關于使用 Angular 2 在 Asp.net MVC 中檢測到自引用循環的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!