Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
user919426 Avatar asked Mar 24 '15 03:03

user919426


People also ask

What is the max size of Varbinary?

varbinary [ ( n | max) ] Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes.

What is Varbinary datatype?

VARBINARY: A variable-width string up to a length of max-length bytes, where the maximum number of bytes is declared as an optional specifier to the type. The default is the default attribute size, which is 80, and the maximum length is 65000 bytes. VARBINARY values are not extended to the full width of the column.

What are the different types of properties supported in Entity Framework?

An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.


1 Answers

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.

like image 97
DrewJordan Avatar answered Oct 17 '22 00:10

DrewJordan