Mapping object type property to varbinary(MAX) in Entity Framework

c# ef-fluent-api entity-framework wcf


I have a situation where I have a type with a property of type object, eg.

public class MyType
   public virtual object MyProp{get; get;}

This type will have to be:

  1. Saved using Entity Framework to a database, as a byte[] (I have figured the serialization logic)
  2. Transmitted through WCF (I will use the KnownType attribute)

How do I map my object property ensuring that it is converted it to a byte array for storage?

N.B: The object property will be a value type(non-complex)

I thought of creating a separate type for saving to the database e.g:

public class MyTypeEntity
   public virtual byte[] MyProp{get; get;}

How do I convert/translate between the types while still able to define the relationship mappings?

Does this involve some sort of interception on saving?

The best solution I could think of without breaking my back is simply storing the serialized data in the DB.

If there was some form of property covariance in C#, maybe this would've worked easier. As far as I know, it does not exist. If there is an elegant alternative that I can use, I would appreciate your insight.

3/24/2015 7:42:49 AM

Accepted Answer

I would recommend keeping a byte[] field on your entity; your class should really mimic the database structure as closely as possible. One way I've done something similar to this in the past is to create a separate class file (remember, your entities are partial) and add a NotMapped property to the second file. You can make the getter and setter do the conversion from object to byte[] and in your code, just always interact with the object property that EF will ignore. It's pretty painless, and EF will still track the varbinary field to the byte[] that you don't directly access.

3/24/2015 7:19:25 PM

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