Saving and retrieving a serialized object with the first Entity Framework 6.1 code

Example. Let them say that I have these three classes. Foo is a proper Entity Framework object with DbSet, whereas I want my EF DbContext not to know about Bar and Baz , because I marked the Foo Bar property with my SerializedColumn attribute. Using this attribute, I want EF to serialize the Bar instance with its Bazes into a single string field and transparently deserialize Bar into a Bar object when Foo materializes EF.

 public class Foo { public Guid Id { get; set; } [SerializedColumn] public Bar Bar { get; set; } // .. } public class Bar { public string Name { get; set; } public Baz[] Baz { get; set; } // .. } public class Baz { public string Name { get; set; } // .. } 

The columns of the Foo table look like this:

 [Id] [uniqueidentifier] NOT NULL [Bar] [nvarchar](max) NULL 

And when I request Foo , I return to the Bar property, which is already deserialized. When I insert or update Foo , the Bar property gets serializable EF without having to think about it. The only thing I need to do is add the [SerializeColumn] attribute to the properties.

Purpose:

  • I'm not necessarily looking for a full-blown solution (although I would have accepted it), but for guidance on where to go to the EF pipeline, and how to do it. I.E. what EF classes, configurations, conventions, etc. need to be taken into account?
  • I want to create Migrations, as expected. That is, I would not want my Bar property to turn into the Bar_Id field, which points to the Bar table. Instead, I want the nvarchar(max) "Bar" field, which will contain the serialized version of the Bar object. If this is simply not possible, say so in your answer.

Notes:

  • The idea for this came about after watching the video of Building Applications with Entity Framework 6 by Rowan Miller.
  • ComplexType does not meet my needs. I need deep serialization and no need to filter or sort any properties of what was serialized.
  • I plan to serialize using the Newtonsoft JSON library, but how serialization happens is not a big deal.
+7
entity-framework ef-code-first entity-framework-6 ef-migrations
source share
2 answers

The only solution is

 public class Foo { public Guid Id { get; set; } // Not Mapped attribute will make EF // ignore this property completely [NotMapped] public Bar BarObject { get; set; } public string Bar{ get{ return JsonConvert.Serialize(BarObject); } set{ BarObject = JsonConvert.Deserialize<BarObject>(value); } } } 

Updated as suggested by @zds

+9
source share

It is not possible to do this without changing the EF. With EF 6, I think a few people did this using a text box and some restrictions (Bar and Bar children do not have access to the saved EF property or you need other work after deserialization).

+1
source share

All Articles