Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 424
Imran Rizvi Avatar asked May 29 '13 10:05

Imran Rizvi


3 Answers

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.

like image 61
Marc Gravell Avatar answered Oct 23 '22 13:10

Marc Gravell


if you use entity framework 5.0 or above Add [Serializable] tag between this code:

<#=codeStringGenerator.UsingDirectives(inHeader: false)#>

[Serializable]

<#=codeStringGenerator.EntityClassOpening(entity)#>
like image 12
nazim hatipoglu Avatar answered Oct 23 '22 13:10

nazim hatipoglu


For Entity Framework 6, Add Serializable above this two parts at Model.tt

[Serializable]
Partial <#=Accessibility.ForType(complex)#>

[Serializable]
<#=codeStringGenerator.EntityClassOpening(entity)#>
like image 10
Tony Dong Avatar answered Oct 23 '22 14:10

Tony Dong