0

I'm trying to write a class to the database using entityframework.

public class MyClass
{
    [Key]
    public long ID {get; set;}

    public Type MyType {get;set;}
}

My DbContext contains a DbSet of MyClass, but when I try to create the DB,
I get this exception:

System.InvalidOperationException: 'The entity type 'CustomAttributeData' requires a primary key to be defined.'

I'm guessing it's because EF is trying to use the inner structure of System.Type.

Is there a way to make EF write this field (or any other classes we can't change) to the DB?

Idov
  • 5,006
  • 17
  • 69
  • 106
  • 1
    But how it is supposed to be serialized to the DB ? What kind of field this is supposed to be in your DB ? – Pac0 Oct 07 '17 at 17:14
  • @Pac0: binary format. – Idov Oct 07 '17 at 17:22
  • May I ask what is your goal with this ? What functionality are you trying to achieve ? – Pac0 Oct 07 '17 at 17:32
  • @Pac0: I don't know what other properties will be added to the class. I'd like not to serialize each property to JSON like this. – Idov Oct 07 '17 at 17:50

1 Answers1

1

Why serializing the type itself? I think that storing its full name should be enough:

Ignore MyType property using NotMapped attribute and serialize the type name instead the type itself (MyType.FullName) and create it back using Type.GetType().

Note: for complex custom types, an elegant solution can be found here.

[Edit] Since Type actually may be a custom complex type, a possible solution is using JsonConvert.SerializeObject and JsonConvert.DeserializeObject to obtain regular strings that can be directly stored into the database.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • ok, but it's not only that property. There will be other "complex" properties. (BTW - Type is not that object's type... its something else) – Idov Oct 07 '17 at 17:02
  • @Idov - then take a look upon the suggested solution which basically uses Json.NET to serialize and deserialize complex objects to and from a string representation. You should also replace `Type` (aka. System.Type) with `CustomType` or something similar to avoid confusion. – Alexei - check Codidact Oct 07 '17 at 17:05