WCF can't serialize cyclic references - c#

I have a database with a lots of relationships between Tables and a Silverlight client that connects to my server with WCF service on ASP.Net side.
First i used LINQ to SQL as a robust mapper tables to object and in a WebMethod that returns a List<Foo> of my Database's object(suppose GetFoo()). The Foo has lots of relationships with other objects that each of that have lots of realaships too,(this means , there is a PK and FK between tables).also i use Microsoft Service Trace Viewr for track my service
When i call GetFoo() , WCF returns this error:
Object graph for type 'X.Y.Z' contains cycles and cannot be serialized if
reference tracking is disabled
I searched this error and find this great post but that is not working properly and i see same error too.

Various options:
remove the cyclic dependencies from your model; this might be tricky for a generated model that has lots of existing code built against it, but is worth a try; however, you typically want to not serialize the parent, which is exactly what LINQ-to-SQL wants you to keep (it'll let you drop the children property, but that is what you usually want to serialize)
enable cyclic references; it looks like you've tried this without success; did you enable it at both ends, though? Actually I wouldn't be surprised if Silverlight doesn't like this extension (it has limited extension support)
use a separate (flat) DTO model for data transfer purposes
try using NetDataContractSerializer; I can't remember if this is supported in Silverlight, and I must admit I'm not its biggest fan, but it might be a pragmatic fix here
I'd vote firmly in the "DTO model" category; simply, having a separate model means you are less likely to run into tangles whenever you tweak the DB - and you are in complete control over it.

A bit late this. But if anyone are using linqtosql and have this problem you can simply just open the tables in your dbml class. Right click next to a table and click properties.
HEre there is a property named Serialization Mode.. Set it to Unidirectional
The error will be gone

I know this is an old question now, but did you try decorating the classes generated by your DBML with [DataContract(IsReference=True)]?
I had the same problem in 2010 and had to resort to some fairly extreme measures to get it to work on client and service sides, but recently went back through it with VS2013/.NET 4.5 and had much less pain, as documented here (with EF v6 RC 1 POCO objects): http://sanderstechnology.com/2013/more-with-the-entity-framework-v6-rc1/12423/

Related

Breeze Custom Actions

I've been using BreezeJS in a number of projects for a while now, and I have to say that in most ways, it makes your life MUCH easier, which is why I keep coming back to it. However, I seem to consistently run into a scenario where it falls completely flat, and I cant seem to find any "correct" way of working around this issue.
Let me explain. One of the best things about BreezeJS is that it follow this UoW pattern that allows you to save entities using the saveChanges method of the entity manager, like EF.
However this is also a part of the problem, because as you develop more and more sophisticated application, I sometimes feel this approach is not always appropriate. I find that often I have:
Operations that doesn't really involve creating entities on the client, but rather involve executing an action on the web api that may result in the creation of various entities or other forms of state on the server, that should then be send back to the client.
Operations that involve entities with properties, that cannot be saved because some of them are private to the server, and should not be put on the client (often solved with a JsonIgnore for the client, but comes with issues when you start persisting the given entity again)
I feel that there is one thing that could solve these issues relatively easily, and it is a concept that already exists in OData: Actions. Actions that can be performed globally, on entity sets or on specific entities and then return either custom objects or entities that will be directly tracked by BreezeJS.
Currently, I find myself doing the following workaround (which I don't know if is appropriate):
Make a "Resource" action on the BreezeController that represents an action rather than an an actual resource. This takes in a custom parameter object and returns a non-entity object, that may contain actual entities (as described under "Cool Breezes" with the Lookups, because these will then be track by BreezeJS)
Use the "ajaxpost" breeze lab to allow querying a resource with a POST instead of a GET so any sort of arguments can be passed in.
Is there a more appropriate way of accomplishing something like this? Are there future plans to support custom actions?
An approach I have seen to solve this type of operation, is to simply make these sort of operations "around" the breeze api controller. That is, simply using an ApiController that has nothing to do with breeze. But I kinda feel this defeats the purpose of breeze, because then, if the operation results in the creation or deletion of entities, you must start tracking them by yourself on the client, by either creating them locally, or by issuing another breeze query to go get them. This really gets tiresome if you need a lot of these types of operations.
I’m struggling with the same issue myself. I have an app that uses breeze to store trades in a SQL database and after the trade is stored, another user can use the app to send the trade to a backend trading system. I created an OData action to do the import to the external trading system so I can do a post to /trades(123)/ImportTrade. When I get the metadata for the service using /$metadata it sees that the trades entity has this action (it's in the metadata).
I was hoping that breeze would see this in the metadata and create a method on the trades entity to do a post to my OData action, but it does not. This would be a great feature if it was added to breeze (exposing OData actions as methods on entities).
As a workaround I have extended the breeze entity myself with a custom method that does the post to /trades(???)/ImportTrade.
It would be great if breeze could handle this for us!
Your approach using ajax post is a good way to do thouse kind of things...
You can also make your own context by inheriting from BreezeContext that has nothing to do with a DB, and do your actions there with out saving the entites and still get the result back as a non tracked object or entities.
If you create a new entity on the server (not always a good idea with breeze, but still can still be done) you have to make sure that breeze will still generate the temp keys for that entity.
You can use the temp key generator or just delete the primary keys of the non tracked object.
You can use the metadata of that entity type in order to get it's primary key properties and then delete them using javascript like so: delete obj[prop]
then use createEntity with the non tracked entity that doesn't have primary keys.
Breeze will then generate the primary keys for you and your all set.
I also hope that Breeze will address the need to do custom actions that may return a custom non tracked object in a more intuitive way
Hope this helps

Mapping Tool like EF Designer but for Data objects?

In trying to separate my domain layers and GUI and looking into all the different ways to do that, one thing that I keep asking is why is this so difficult? Why all the extra code for data obejcts and then all the extra mapping of properties copying values in and out etc. Shouldn't theere be an easier way?
Then I remeembered when i used to wite small littler db app using MS Access and, Access has the concept of a Dynaset, basically a Dynaset is a View, just like an SQL Server View, except it is an updateable view. So, a MS Access form would be based of the View/Dynaset and therefore would not have to know the details of all the individual tables involved. Sounds like the Data objects pattern to me. Now, since Access has had this for 2 decades, shuoldn't there be a similar Dynaset, View, Mapping tools for Entity Framework, one that abstracts away the entities from the presentation? Is there one I am not aware of? 3rd party?
Thoughts on this?
If I understand you correctly, you may be looking for Entity Framework with POCO entities. You can find templates for them in the online gallery for templates (when you Add New Item in the project). Alternatively you can use right-click in your .edmx design view, select "Add code generation item" and pick the Fluent Generator.
These methods create multiple files instead of the default all-in-one EF generated file. One such file is the DbContext (as opposed to ObjectContext), one contains only entities (in the form of regular C# objects, no attributes or anything, just plain objects) and the last contains generated mapping in the form of fluent rules.
In this phase you can de-couple the entities file from its template and move it to another assembly. And voila, you have entities independent on the EF infrastructure. You can just pass the context these entities like you would before, and it'll do mapping by itself.
Alternatively you can use tool like AutoMapper, but you'll have to provide the mapping manually, which is a lot of work, but may be good in some cases.
Good design requires work. If it was easy, everyone would do it automatically. After all, everyone wants to do the least amount of work possible.
All the things you are complaining bout are part of the good design process, and there is no getting around them if you want a good design.
If you want to take shortcuts, then by all means, skip them. It's your code. nothing requires you to do things any specific way.
Access can do a lot of things because it's a desktop application, not a web application. Web applications are fundamentally different from desktop applications in how you design them, how they work, and what issues you face with them. For instance, the fact that you have a stateless environment and cannot keep result set from request to request makes many of the things people take for granted in Access impossible to do in a web app.
Specifically, if you want to use views, you can do so. Views are updateable if they are properly designed, but typically require update statements that only affect one table in the view). EF can work with views as well, but it has a lot of quirks you must deal with.
The data mapper pattern has emerged as a common pattern in web design because it's the easiest and straight forward way to have clean separation of concerns between layers and/or tiers. I suggest you find ways to make them work within your development process.
It may also be that MVC is not the most appropriate framework for you to use. It sounds more like you want to build Web apps the way you did Acceess, in which case Visual Studio Lightswitch may be a better choice for you.
http://msdn.microsoft.com/en-us/library/ff851953.aspx

Logging Data Base changes using Entity Framework and ELMAH (or else)

Our customer request the functionality of logging changes in db.
We need next structure:
"Timestamp", "User", "DB.Table.Field changed", "Value after change"
What we have:
Entity Framework Code First
ELMAH
MySQL Data Base with more than 100 tables (changes should be tracked to all of them)
So we need:
Somehow track what table was changed
What new value was added/updated
Generic functionality (if possible)
Any ideas how to do this?
PS. ELMAH is not a strict requirement. But MySql is :)
Thank you!
Ultimately, what you're looking for is some sort of behavior that keeps track of auditing. ELMAH is not geared towards that.
You most likely want to look in to some sort of Polymorphic object that can keep track of who executed what type of action on a known entity. You're most likely going to want to use some sort of AOP concepts. Libraries like like DynamicProxy2, LinFu should be helpful in this area.
Your goal would be to use proxy objects that wrap your existing entities and "inject" the auditing information that you need to track.
I actually had the same feature request and even though I wrote a tracking layer before for my generic repository I found that there is one available in Nuget/Github that handles this.
https://www.nuget.org/packages/TrackerEnabledDbContext/
https://github.com/bilal-fazlani/tracker-enabled-dbcontext
You can use this and I found that it works great for me. I use it into my Generic repository project.

LINQ to entities ... without the entities (if possible)

Sounds daft i know but i want to do something a bit out of the ordinary ...
essentially I'm looking to build solution that has a wcf data service at the back end (or something of that ilk at least) that allows me to query my database using simple url syntax.
the problem i have is that when my db schema changes i have to recomile the entire back end and that's not good because the solution i'm building allows the definition of "entities" so to speak.
Essentially what i want to do is have the model update every time the db updates ... as a sort of triggered event.
I'm thinking that EF won't do this which leads me to my actual question ...
How would you solve this problem?
I need exactly what a wcf data service offers out of the box ... just with a more dynamic data model beneath it.
You need to change the O/RM to something more dynamic ... something like Massive could be used instead of EF.
Someone looks to be doing similar with WebWCF ... Massive with WCF Web Api to return dynamic types/Expandos?.
If you use data services then you'd need to figure out some way to represent the Massive as a 'DataContext'. WebWCF on the other hand would serialise dynamic objects as a lump of JSON or XML where required.
The problem with your proposed approach is one where the Web Service contract is dynamic and not versioned. This means that if you delete/rename/change a field you essentially have created a change to the 'Contract' that the clients use to consume the web service. This can lead to a client breaking unless updated at the same time.
If you are looking at a low friction way of managing model change updating database I have found that EF Code First 4.2 and EF Migrations works pretty well for me. 0.7.0.1 is reasonably stable and all available from NuGet.

Entity Framework Self Tracking Entities on a N-Tier application

This is a general architecture question, hopefully to folks out there already using EF in final applications.
We have a typical N-Tier application:
WPF Client
WCF Services
EF STE DTO's
EF Data Layer
The application loads all known business types during load time (at the same time as the user logs in) then loads a very large "Work Batch" on demand, this batch is around 4-8Mg and is composed of over 1.000 business objects. When we finish loading this "Batch" we then link everything with the previously loaded business types, etc...
In the end we have around 2K-5K business objects in memory all correctly reference so we can use and abuse LINQ on the client side, we also do some complex math on all these objects on the client side, so we really need the large graph.
The issue comes when we want to save changes to the Database. With such a large object graph, we hardly want to send over everything again through the Network.
Our current aproach, which I dislike, given the complexity of the T4 templates so far, is to detach and attach everything on update. We basically want to update a given object, detach it from the rest of the graph, send it over the network, updated it on the WCF side, and then reattach it again on the client side. The main problem is when you want to update linked objects, let's say you add something that has a reference for something that is also added, then another reference to something modified, etc. This forces a lot of client code to make sure we don't break anything.
All this is done with generated code, so we are talking about 200-800 lines of T4 code per template.
What I'm looking at right now is a way to customize serialization and deserialization of the STE's, so that I can control what is sent over the network or not, and be able to update batches instead of just a single STE. Checking references, see if those references are Unchanged or not; if not don't serialize, if yes serialize and update everything just by attaching it to the context on the WCF side.
After some studying I found 2 solutions to this method.
One is by writing a custom DataContractSerializer.
The second one is by changing the STE template created by EF and playing around with the KnownTypeAttribute, instead of generating it for each reference type, have it reference a method that inspects the object and only marks for serialization references that are not unchanged.
Has anyone ever come across this
issue before?
What solutions did you use?
What problems did you encounter down
the line?
How easy was it to maintain the
templates created?
I don't know whole application design but if you generally load the work batch to the service and then send it to the client to play with it, it looks like service layer is somehow unnecessary and you can directly load data from database (and you will get much better performance). Depending on complexity of computation you can also do some computation directly in the database and you will again get much better performance.
Your approach to save only part of the graph is abuse to STE concept. STE works in manner - you load the graph, modify the graph and save the same graph. If you want to have a big dataset for reading and save only small chunks it is probably better to load data set for reading and once you decide to update a chunk, load only the chunk again, modify it and send it back.
Interfering the internal STEs behavior is imho the best way to lost some changes in some corner / unexpected scenarios.
Btw. this somehow looks like a scenario for syncing local database with a global one - I have never done that but it is quite common in smart-clients.

Categories