How to add Serializable attributes in all entities generated by Entity Framework 5.0

c# entity-framework


I am using EF 5.0 to generate POCO entities and using it in a seperate Data Access layer

I want to tag all the entities [Serializable]

How to modify template to add Serializable attribute?

5/29/2013 10:15:49 AM

Accepted Answer

Following are the steps to do so:

1) Open the file

2) Locate following string in this file


3) Write [Serializable] above this line, so the code will look like this


Save the file , open the entity file, you can see that it has the desire tag written, you don't even have to generate entities again.

5/29/2013 10:15:49 AM

Expert Answer

If you don't want to edit the template, you can also do this in a separate code file - because of the convenience of partial classes. So if the types here are Foo, Bar and Baz in the My.Namespace namespace, you can create a separate file in the same project, with:

using System;
namespace My.Namespace {
    [Serializable] partial class Foo {}
    [Serializable] partial class Bar {}
    [Serializable] partial class Baz {}

This will then be merged with the generated half, applying the [Serializable] attribute. It will also allow you to add your own methods to the types, or to provide the body for any partial method implementations that the template declares.

I should, however, caution you: [Serializable] suggests you are using BinaryFormatter; this is not necessarily a good candidate. It would be preferable to look at contract-based serializers. I would be very surprised if the EF template did not already have the option to output attributes for DataContractSerializer (specifically, [DataContract]/[DataMember]). BinaryFormatter can be very problematic as you version your software.

5/29/2013 10:25:32 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow