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:
Entity Framework
to a database, as a byte[]
(I have figured the serialization logic)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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With