does linq-to-sql entity serialization work out of the box? - linq-to-sql

If I try to serialize a linq-to-sql entity, will it by default serialize only the primitive fields or will it try to access the relationship fields as well? If it tries to grab relationship fields, is there a way to override this?

Which serializer are you using?
The DataContractSerializer will
include loaded relationships but not
those that are not yet loaded / null.
The XmlSerializer tend to choke on relationships if they are bidirectional (i.e. entity A points to entity B which in turn points back).
The binaryformatter ... I never got that one to work properly with L2S entity objects having relationships to other entities. Long time since I tried though, so maybe I just did something wrong...

Another point to add to the accepted answer:
Relationships that are not collections will never be serialized by DataContractSerializer (whether they are loaded or not), because no DataMember attribute is generated for them from the .dbml file.
I found here an explanation by then-at-Microsoft Daniel Simmons:
The issue here is that prior to SP1 there was really no good way with DataContract serialization to handle graphs of objects that had cycles. As a result for LINQ to SQL the compromise decision was made to allow users to opt-in for uni-directional serialization and to only serialize collections not references. This mechanism doesn't work well for cases where you really want to serialize a reference (like your scenario above), but it at least gets you going for some common scenarios.
In SP1 new support was added to WCF which enables DataContract serialization to deal with cycles, but it is something you must opt-in to by changing some of your DataContract attributes and potentially also making changes to your collection and reference class implementations to properly handle the serializaiton and especially the deserialization behaviors of WCF. In the Entity Framework the changes were made to take advantage of these new features since it had not yet released its very first version, but Linq to SQL only had a small service-pack upgrade in sp1 and it was not modified to take advantage of this capability.
I have not experimented with this on L2S, but it might be possible to generate your own classes which work with L2S and have the right support for WCF serialization with cycles.
Danny

Related

How to use the Jackson object mapper with Java 17

I'm trying to implement a logic that serializes and de-serializes a very complex legacy object. The object contains other complex objects inside of it that are spread through various other projects. There are even some JAXB1 objects that are generated from an xsd schemas and are part of the chain.
Right now there is already a working version that uses XStream and this worked for years. But since Java 17 there are issues because of the new restriction for using reflection on private fields from different modules. Exceptions like this started to appear ->
Module {A} does not 'opens {package}' to {B}". One of the things that bothers me is that all of these packages are from some third party libs and I even can't find any objects from them in the model chain.
So I started implementing a new serialization based on the Jackson databind API but right now I'm wondering is it going to solve the issues at all? Does Jackson also use reflection in case to serialize and de-serialize? What is the best way to configure the ObjectMapper and what should I change in the objects that I need to work with in case to make the reflection usage as low as possible?
Right now I've configure the ObjectMapper as:
objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
and I'm annotating all fields that should be serialized with #JsonProperty but I'm not sure that this is going to help. Okay, I assume I must have getters and setters, but should I also annotate them? Does the annotation has something to do with the reflection usage at all?

Jackson support for polymorphism without annotations and dedicated bean fields

Is there a way to perform serialization/deserialization in Jackson of polymorphic classes w/out using annotations or specialized bean fields? I have to support class hierarchies that I cannot modify and don't wish to use annotations.
I'd like to be able to designate a synthetic name, which would not be in the classes that I am serializing/deserializing, that would be inserted into the JSON representation and used to identify the type.
If mix-ins are not to your liking, there isn't anything pre-defined to pass, but you can relatively easily achieve this by sub-classing JacksonAnnotationIntrospector and configure mapper with it.
In your implementation you can override all aspects of annotation access: in your case it's probably enough to override findTypeResolver() (and if you want per-property overrides, 'findPropertyTypeResolver()').
The method can then use whatever mechanism you want to construct TypeResolverBuilder (most likely StdTypeResolverBuilder) that contains same information as what would usually come from #JsonTypeInfo annotation.
For anyone looking for polymorphic json unmarshaling problems, you should check out this post, which gives great examples & workarounds for JSON serialization / deserialization caveats.
And if mixins (step 5 at the above mentioned post) is not what you're looking for than go for the accepted answer by StaxMan.

Debugging Entity Framework DBContext API Mappings

I am mapping some pre-existing Business Objects to our database using Entity Framework. These object were originally using a home-grown data access method, but we wanted to try out Entity Framework on it now that it is using Code-First. It was my expectation that this would be fairly simple, but now I am having some doubts.
I am trying to use only attributes to accomplish this so that I don't have some of the mapping here, some of it there, and still more of it over there....
When I query for entities, I am getting System.Data.Entity.DynamicProxies.MyClass_23A498C7987EFFF2345908623DC45345 and similar objects back. These objects have the data from the associated record there as well as related objects (although those are DynamicProxies also).
What is happening here? Is something going wrong with my mapping? Why is it not bringing back MyBusinessObject.MyClass instead?
That has nothing to do with mapping. Those types you see are called dynamic proxies. EF at runtime derives class from every type you map and use it instead of your type. These classes has some additional internal logic inside overriden property setters and getters. The logic is needed for lazy loading and dynamic change tracking of attached entities.
This behaviour can be turned off in context instance:
context.Configuration.ProxyCreationEnabled = false;
Your navigation properties will not be loaded automatically once you do this and you will have to use eager loading (Include method in queries) or explicit loading.

Migrating from LINQ to SQL to Entity Framework 4.0 - Tips, Documentation, etc

I tried out EF back in .NET 3.5 SP1, and I was one of the many who got frustrated and decided to learn LINQ to SQL instead. Now that I know EF is the "chosen" path forward, plus EF 4.0 has some exciting new features, I'd like to migrate my app to EF 4.0.
Can anyone suggest any good resources that are specifically targeted towards 4.0 and L2S migration? NOTE: I can find plenty of blogs and articles related to migrating from L2S to EF on .NET 3.5, but I feel like many of those were obviously dated and unhelpful to someone using 4.0.
I'd really like as much deep, under-the-hood stuff as I can get; I want to really come away feeling like I know EF 4.0 the way I currently know L2S 3.5.
TIA!
I have done loads of this very type of conversion and FWIW, I would say there are more similarities than differences. I don't think there is any definitive documentation that will make you feel like an expert in EF4, beyond the stuff that is already out there...
http://msdn.microsoft.com/en-us/library/ex6y04yf(VS.100).aspx
What I can give you are the more obvious "gotchas." Specifically, Linq2Sql wanted to combine the business layer and the data layer a lot more obviously. It really pushed you to create your own partial classes. I could go on and on about way, but the most specific reason is the way the one-to-one mapper will create public parent and child properties for all relations.
If you attempt to use any type of serialization against this model, you will like run into circular reference problems as a serializer moves from a parent to a child and then back to the parent as the Linq2Sql serialization behavior automatically includes all children in the graph. This can also be really annoying when you try to grab a customer record to check the "Name" property and automatically get all the related order records included in the graph. You can set these parent and child navigation properties to be either "public" or "internal" which means if you want access to them, but don't want the serializers to automatically create circular references, you pretty much have to access them in partial classes.
Once you start down the partial class path you generally just continue the pattern and eventually will start to add helper methods for accessing your data into your individual entity classes. Also, with the Linq2Sql DataContext being more lightweight, you often find people using some kind of Singleton pattern or Repository pattern for their context. You don't see this as much at all with EF 3.5 / 4.
So let's say you have some environment similar to the one described and you want to start converting. Well, you need to find out when your DataContext is going to be create/destroyed...some people will just start each Business Layer method with a using() statement and let the context pretty much live for the lifetime of the method. Obviously this means you can get into some hairy situations that require adding .ToList() or some other extension method to the ends of your questions you can have a fully in-memory collection of your objects to pass to a child method or whatever and even then you can have problems with attempting to update entities on a context that they weren't originally retrieved from.
You'll also need to figure out how to much of the BusinessLogic incorporated in your Linq2Sql partial classes out into another layer if it doesn't deal explicitly with the data operations. This will not be painless as you figure out when you need/don't need your context, but it is for the best..
Next, you will want to deal with the object graph situation. Because of the difference in the way lazy-loading works (they made this configurable in EF 4.0 to make it behave more like Linq2Sql for those who wanted it) you will probably need to check any implied uses of child objects in the graph from your Linq2Sql implementation and verify that it doesn't now require an explicit .Include() or a .Load() to get the child objects in the graph.
Finally, you will need to decide on a serialization solution in general. By default, the DataContracts and DataMember attributes that are generated as part of an EF model work great with WCF, but not at all great with the XmlSerializer used for things like old .asmx WebServices. Even in this circumstance you might be able to get away with it if you never need to serialize child objects over the wire. Since that usually isn't the case, you are going to want to move to WCF if you have a more SOA, which will add a whole new host of opportunies, yet headaches.
In order to deal with the partial classes situation, and the hefty DataContext and even the serialization issues, there are a number of new code-generation templates available with EF 4.0. The POCO-Entity template has a lot of people excited as it creates POCO classes, just as you'd expect (the trouble is that excludes any class or member attributes for WCF etc etc). Also, the Self-Tracking Entities model pretty much solves the context issue, because you can pass your entities around and let them remember when and how they were updated, so you can create/dispose your contexts much more freely (like Linq2Sql). As another bonus, this template is the go-to template for WCF or anything that builds on WCF like RIA Services or WCF Data Services, so they have the [DataContract], [DataMember], and [KnownType] attributes already figured out.
Here is a link to the POCO template (not included out of the box):
(EDIT: I cannot post two hyperlinks, so just visit the visualstudio gallery website and search for "ADO.NET C# POCO Entity Generator")
Be sure to read the link on the ADO.net team blog about implementing this. You might like the bit about splitting your context and your entities into separate projects/assemblies if you fall into the WebService vs. WCF Service category. The "Add Service Reference..." proxy generation doesn't do namespaces the same way "Add Web Reference..." used to, so you might like to actually reference your entity class assembly in your client app so you can "exclude types from reference libraries" or whatever on your service references so you don't get a lot of ambiguous references from multiple services which use the same EF model and expose those entities...
I know this is long and rambling, but these little gotchas were waaay more of an issue for me than remembering to use context.EntityCollection.AddObject() instead of context.EntityCollection.InsertOnSubmit() and context.SaveChanges() instead of context.SubmitChanges()...
For EF Code First, it's mostly about reverse engineering the existing tables into EF classes. EF Power Tools now does this for you:
http://msdn.microsoft.com/en-us/data/jj200620.aspx
The rest is the obvious work of modifying your existing code to use those generated classes to talk to the database instead of LINQ to SQL.

Specification Pattern defined in Domain

Using Linq to SQL, and a DDD style Domain Layer with de-coupled repositories, does anyone have any good ideas on how to implement a specification pattern without bleeding L2S concerns up into the domain layer, that is still understandable? :)
We have complex business logic surrounding the selection of a set of transaction data, and would like those rules/specifications to be owned by the Domain. We've also done a good job of keeping our domain persistence ignorant.
This presents a problem, because in order to implement a Specification, the domain (as far as I can tell) needs to see the types being queried (L2S types).
Any ideas?
Also, nHibernate is out of the question for reasons I don't want to explain.. :)
Have you considered mapping your generic Specifications into an Expression tree that would translate into proper L2S syntax? It seems that is the main problem you are hitting here. The Specification pattern isn't the problem, but the mapping to L2S is.
Linq-To-Sql classes can be partial. This means that you can extend them by implementing a partial that implements a common interface. That Interface can be shared between layers without the "bleeding" problem you are describing. The rest is just the details of your "IsStatisfiedBy" which should be easy to encapsulate.
I recently had the same issue. Different pattern, but still LINQ to SQL (L2S). I tried two different ways to avoid the leakage.
First we tried using DTOs and a mapping layer. So we wrote super simple objects that had a one to one mapping to the tables. They were all decorated with L2S attributes. We then wrote a mapping layer to map the DTOs to our business objects. All of this was hidden via the Repository pattern from Doman Driven Design. So consumers of the business objects had no idea the L2S was under the hood.
Next, mostly for variety. We tried using the XML mapping features of L2S so the objects themselves needed no attributes. For collections we exposed IEnumerable instead of any of L2S collections. If you looked at the internals of the business classes you could still detect some usage of L2S (EntitySet or Ref). But consumers of the class had no idea. So some bits of leakage but nothing drastic.
In the end we stuck with the first pattern. The second worked and we could have replaced L2S without changing the interface of the business layer, but I was never happy with XML mapping. The first pattern had a much cleaner separation between the database and the business objects. It took more code. The first one also worked better for us because it allowed us to evolve the business objects differently than the tables. In the early days of the project the xml mapping worked because our objects were pretty much one to one with the tables.
So in the end we put a layer between L2S and the domain. It worked. It took more code, but it was really simple stuff. And it was all very testable.
If you want to avoid referencing Linq2Sql from your domain layer, you must work against interfaces that represent your entities instead of working with the actual entities themselves. You then need a mapping layer between your interfaces and your entities.
I've worked this way and found it to be a severe hindrance. I switched to NHibernate for new projects and for the older projects I simply stopped worrying about the domain referencing Linq2Sql entities directly. Overcoming that restriction is simply too much of a time-cost in my opinion.