1

I am using Entity Framework 6.2.0 with my WCF service hosted in IIS. I am getting this error when trying to eager load related table data. I have two tables Product and Category joined by CategoryID.

Trying to fetch products data and their related category Name but getting that error (I have tried almost every solution on web from last 24 hours).

public List<Product> GetAllProducts(int start, int end) { return _context.Products.Include(x=>x.Category).ToList(); } 

I have also set following properties to false.

public Intelliventory_DBEntities() : base("name=Intelliventory_DBEntities") { this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false; } 

App.config

<configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IIntelliventoryService" closeTimeout="10:01:00" openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00" allowCookies="false" bypassProxyOnLocal="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </binding> </basicHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="ServiceBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </endpointBehaviors> </behaviors> <client> <endpoint name="BasicHttpBinding_IIntelliventoryService" address="http://localhost:5050/IntelliventoryService.svc" behaviorConfiguration="ServiceBehavior" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IIntelliventoryService" contract="IntelliventoryService.IIntelliventoryService" /> </client> </system.serviceModel> </configuration> 

Web.Config

<configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.8" /> <httpRuntime targetFramework="4.8" /> </system.web> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IIntelliventoryService" closeTimeout="10:01:00" openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00" allowCookies="false" bypassProxyOnLocal="false" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </binding> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior> <dataContractSerializer maxItemsInObjectGraph ="2147483647"/> <serviceThrottling maxConcurrentCalls="16" maxConcurrentInstances="26" maxConcurrentSessions="10" /> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <directoryBrowse enabled="true" /> </system.webServer> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <connectionStrings> <add name="Intelliventory_DBEntities" connectionString="metadata=res://*/ADOModel.csdl|res://*/ADOModel.ssdl|res://*/ADOModel.msl;provider=System.Data.SqlClient; provider connection string=&quot;data source=RAO-HAMMAS-PC;initial catalog=Intelliventory_DB;persist security info=True; user id=admin;password=admin;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings></configuration> 

I don't get this error when i don't eager load category table.

Also if I try to load just specific column, I get this error.

_context.Products.Include(x=>x.Category.CategoryName).ToList(); 

A specified Include path is not valid. The EntityType 'Intelliventory_DBModel.Category' does not declare a navigation

Category Table from Db Context

public int CategoryID { get; set; } public string CategoryName { get; set; } 

Product Table from Db Context

public partial class Product { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Product() { this.Purchases = new HashSet<Purchase>(); } public int ProductID { get; set; } public string ProductName { get; set; } public int CategoryID { get; set; } public System.DateTime Date { get; set; } public double Quantity { get; set; } public string Model { get; set; } public string Details { get; set; } public double SellPrice { get; set; } public double PurchasePrice { get; set; } public int SupplierID { get; set; } public Nullable<double> PaidAmount { get; set; } public Nullable<int> NoOfSales { get; set; } public Nullable<double> DueAmountToPay { get; set; } public Nullable<System.DateTime> ExpiryDate { get; set; } public virtual Category Category { get; set; } public virtual Supplier Supplier { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Purchase> Purchases { get; set; } } 

As @Andy pointed that Category is not ICollection also Supplier is not ICollection but Purchases is ICollection. But it was all auto generated. Did i do something wrong ?

enter image description here

This is what happens during data fetch event (SSMS Live Event)

enter image description here

Update: I created a console app and directly used EF and it worked

enter image description here

But again when i used WCF in this console app to fetch Products, i got same error !

StackTrace of Exception

System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary() at Intelliventory.IntelliventoryService.GetAllProductsCompletedEventArgs.get_Result() in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 321 at Intelliventory.UserControls.ProductControl.ClientOnGetAllProductsCompleted(Object sender, GetAllProductsCompletedEventArgs e) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\UserControls\\ProductControl.xaml.cs:line 89 at Intelliventory.IntelliventoryService.IntelliventoryServiceClient.OnGetAllProductsCompleted(Object state) in E:\\2- Development\\2-NATIVE WORLD\\Projects\\Intelliventory\\Intelliventory\\Connected Services\\IntelliventoryService\\Reference.cs:line 1082 at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at Intelliventory.App.Main() 

All three Exceptions !

enter image description here enter image description here enter image description here

Update: i have got the exception details (Category contains Cycles)

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

enter image description here

41
  • Where is the database located? The error indicates the application could not connect to the database. The config shows : address="localhost:5050/IntelliventoryService.svc". So is the database on the IIS server or someplace else? On a IIS server the application is run with GUEST privileges and the connection may be denied due to the owner of the connection. Commented May 25, 2019 at 19:39
  • So why do you try to include x.Category.Category? Seeing your model it shouldn't even compile. Commented May 25, 2019 at 20:46
  • @jdweng yes it is hosted in IIS i have mentioned that. and why other features work fine ? even i mean if i remove include thing still it works fine ? Commented May 26, 2019 at 4:09
  • @GertArnold sir ! why should not it compile ? it was all auto generated ..i did nothing .. Category and Products are related with CategoryId. and i am trying to get categoryName when fetching products ! just that .. i used to do that and i guess it work like that ...can you please tell me what looks wrong ? Commented May 26, 2019 at 4:11
  • 1
    Cyclic references. I told you so. Turning off lazy loading doesn't help because the references are loaded. Even with AsNoTracking they will be loaded (at least some of them). The serializer must be told not to serialize reference loops. Commented May 27, 2019 at 17:25

2 Answers 2

1

So finally i found and solved the issue with the help of some really good people :)
Issue was

'IntelliventoryWcfService.Category' contains cycles and cannot be serialized if reference tracking is disabled

So, basically Category contained cycles or circular reference that was causing server to drop the connection. Solution is to put [DataContract(IsReference = true)] on Category class. So the class now look like this.

using System.Runtime.Serialization; [DataContract(IsReference = true)] public partial class Category { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Category() { this.Products = new HashSet<Product>(); } [DataMember] public int CategoryID { get; set; } [DataMember] public string CategoryName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [DataMember] public virtual ICollection<Product> Products { get; set; } } 

Help Reference: http://themvcclub.blogspot.com/2014/11/how-to-fix-WCF-Web-API-Error-contains-cycles-and-cannot-be-serialized-if-reference-tracking-is-disabled.html

Sign up to request clarification or add additional context in comments.

Comments

0

Include is supposed to be the name of the property contains your collection.

Instead of

 Products.Include(x=>x.Category.Category) 

I think that should be:

 Products.Include(x=>x.Category) 

Or

 Products.Include("Category") 

https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

It seems there is only going to be one category associated with a Product so it should be a scalar property.

11 Comments

Both of these didn't work ! i have already tried that . still get same error. but if i remove include thing ..then it works !
You also have defined Category wrongly. See edit above.
thanks for response ! actually it was all auto generated ..i did nothing ..Please see my edit ! i have included full Product class that was generated
And interestingly. Purchases is ICollection but category is not ??? what should i do ? the modification ? can you please tell me ..
Why supplier and Category are not ICollection like Purchases ? something wrong i did with Foreign key mapping ? or what ? i am really confused...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.