I have a LINQ to SQL entity that I will be serializing and returning as JSON over a webservice call.
There is one property on that entity that I would like not to be serialized. For this, there is generally the [ScriptIgnore] attribute, which works exactly the way I want if I manually add that to the designer.cs file.
Now, since the designer file is automatically generated, I would prefer not having to manually edit it, as any changes could easily be overwritten. My question is thus: is there any way to annotate the property so that it is excluded upon serialization, directly in the DBML editor?
If the answer is no; are there any solutions to this that are neater than manually setting the property to null before serializing it, or returning an anonymous type identical except for that one property? In MVC.NET, is there any way to pass parameters to the JSON() method to modify its behavior, perchance?
My apologies if this has been asked before - I'd expect it to be a common question, but I couldn't find anyone like it.
All the DBML generated classes are partial classes so that you can extend them in another file. The DBML designer will only alter classes in the Designer.cs file. Remove the property from the DBML designer and put it in a partial class in another file. You can then add whatever extra attributes you wish, and the DBML designer will leave it alone. You will have to manually manage this property and update it to match any database changes, but I think that is probably a price worth paying if it solves your problem.
If you will have no success with partial classes (which is probably the best way), then you can just serialize the date yourself. It is known that ASP.NET MVC use JavaScriptSerializer to serialize the data. The JavaScriptSerializer have simple and nice customization features like JavaScriptConverter and you can very easy convert the object in something less standard (see use Attr tags for json? for example or all other topics).
To be the most conform to the standards you can define a class derived from JsonResult (for example like here ASP.net MVC returning JSONP or http://dev.qsh.eu/Blogs/Dmitry-P/January-2010/ASP-NET-MVC-Tip--3.aspx) and save serialized data in context.HttpContext.Response directly with a Write method. Then you are absolutely free how you serialize the data to JSON.
Instead of using the partial class answer above you could try going into the DBML designer and setting the access modifier of the property from public to internal. I did this on table to table relationship properties and doing so worked for me to eliminate circular references when serializing my objects to JSON.
Related
This SO question explains how to ignore extra fields when deserializing JSON with Jackson
by using #JsonIgnoreProperties(ignoreUnknown=true), but I want to know when/why should I do this?
This overrides the default for Jackson, which is to throw an exception for unexpected fields. I assume if I should just use this default normally, but when/why would I want to design my system to be strict vs accept anything it can?
I guess this is more of a design philosophy question, so let me know if this is not the right place to ask.
The SO question itself has one of the scenarios as an answer to this question.
The problem is, the JSON objects might change and have new fields added while the application is published, but currently it will break even when a simple String field is added, which can safely be ignored.
There can be various scenarios where you need to ignore some of the json properties while serializing/deserializing JSON like If you are consuming json from a web service and just want few meaningful fields to be serialized. For example from an employee details json, you want just the employee first name and last name. This way you will avoid having a heavy employee object.
If the consumed service upgrades in future adding some fields, your code will continue to work.
ExcludeStrategy in Gson allows you to filter fields based on reference type. But due to polymorphism, we can have an object that contains much more fields. Which basically means ExcludeStrategy is actually useless in this case. I think this was quite a bad design in Gson.
The issue is that by getting the field, you can find out what class/interface that field was declared in, but can't find out what is the actual instance that is currently processed by Gson. So you can't use ExcludeStrategy other than for pretty basic models, not for hierarchies.
Is there a way to tell Gson what fields to log and which to skip, without using annotations, at runtime?
Maybe something like SimpleBeanPropertyFilter in Jackson framework?
There isn't anything for this. I've opened an issue with a suggestion of how to get this outcome, but so far no updates:
https://github.com/google/gson/issues/1272
Follow that issue for an update. I'll also update this answer whenever there's any progress.
i'm just new to ASP.NET and other things with it.. i am using automapper in entity framework which is giving the ERROR.......
this occurs when i tried to get the desired data with JSON response...
System.Data.Entity.DynamicProxies.Account_C2A5EBE3CC4467F8B34569FAEB8687C41333F5D82DB38AC1D2E21FC5F8A47193'.]
i have tried many resources on stackoverflow and on other platforms also but there is no solid solution to this problem.
i have turned on LAZY LOADING using virtual keyword in MODELS.
i don't want to turn off lazy loading using ..
Configuration.ProxyCreationEnabled = false;
i am searching for the other solution to load all the data using the lazy loading ..
If i am going to off lazy loading then other headaches are to face on.
please help me out Seniors ...........
Two options:
Do not serialize the entire entity. Instead, convert it to a more simple class, and then serialize that object. I recommend you to use AutoMapper for object conversion.
If you use Json.Net, you can add the JsonIgnore attribute on top of the properties you want to avoid.
My recommendation is the first option. I think is a good idea to return only the objects you really need. For that purpose, you should have simple model objects and a mapper that transforms between your entities and this model classes. If, for example, all your entity objects are completely connected, there can be the case that you will serialize the entire database, which is not desirable. Try to move out the Entities from the presentation layer.
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.
Say "Foo" is a Linq to SQL entity created in the Linq to SQL designer.
I then have "Bar" which derives from "Foo".
Should I be able to save "Bar" using Linq to SQL (assuming I don't care abut saving any of the extra properties on Bar).
using (myDataContext ctx = new myDataContext())
{
ctx.Foos.InsertOnSubmit(instanceOfBar);
ctx.SubmitChanges();
}
Is this supposed to be supported?
Thanks much,
Jon
I've tried to do this once upon a time and couldn't get it to work. Can't remember what the error that was thrown, but to get around it, i basically had to go through all the properties using reflection and copy the properties marked with ColumnAttribute into a new base class instance and then insert that instead. It's not pretty, but it works. I haven't reinvestigated the issue since i implemented it, so if there's a better way, i'd love to know.
I'm not sure, but why are you doing it? The entities are all implemented as partial classes, so why don't you just implement what you want in a partial class?
I'm a stickler for the repository pattern which means that I define my models in an isolated dll (project.Models.dll) and then create a LinqToSql implementation of my IRepository.
The linq classes only exist within the LinqToSql implementation dll and I create extension methods to convert from my models to the linq entities and vice versa.
I've found that this enables you to test more parts of the system without being overly reliant on the database. It is a bit of a pain though, but you only do it once per project.
Which then means that you have full control over the serialization of your objects, and can do pretty much whatever you like with them