10

I'm currently constructing a database from an existing system with EF and code-first approach.

It is preferred that minimal changes is made to the 'core' classes. Because of this I would like to find a work-around for Structs and EF.

Is it possible to wrap a Struct into a class in any way so that EF can use the data within this Struct? Since EF are able to create its own Proxies of my 'core' classes, shouldn't I be able to this as well?

My knowledge about .Net, C# and EF is rather limited because I started to learn this language this year due to a bachelor assignment.

Any help would be highly appreciated.

Edit: Added examplecode.

Core has many classes that utilizes the TaxMode Struct, and store data in this Struct.

public class AcmeClass
{    
TaxMode Taxmode { get; set; }
}

The Struct is as follows:

public struct TaxMode
{
public string Name { get; set; }
public bool isTrue { get; set; }
}

Any attempt to add the properties of TaxMode into those classes only result in non-nullable errors.

jonas
  • 1,592
  • 3
  • 20
  • 29

2 Answers2

8

Structs are not supported.

You have to use class istead of it.

Updated

take a look at this Ladislav Mrnka answer

Community
  • 1
  • 1
MikroDel
  • 6,705
  • 7
  • 39
  • 74
  • 1
    Isn't there a way to wrap the Struct into a class in runtime or compilation with reflection or something? – jonas Apr 04 '13 at 11:35
  • I didn't get the approach in the link to work. Might just have to do a dirty fix here, and add the structs data as properties into those classes which uses this struct. – jonas Apr 04 '13 at 12:57
  • @JonasBG - to add a struct as a propertie is a good idea. And it will work - if you can really add your structure in your class. After your comments I thought you cannot make any changes in your code. The other way it will be not a big difference to rename struct in a class or to build a struct into another class. – MikroDel Apr 04 '13 at 13:05
  • how I understand it, that example stores an int in the database, which then is populated into an Struct. My way is the other way around. I have a Struct that stores data. And I want these data to be stored in the database. I'm grateful that you are taking your time to help me, though I'm not completely confident with C# code and approaches yet =) – jonas Apr 04 '13 at 13:41
1

Have you considered serialization as below?

[NotMapped]
public TaxMode? TaxMode { get; set; }
public string TaxModeJSON
{
    get
    {
        return TaxMode == null
                   ? null
                   : JsonConvert.SerializeObject(TaxMode);
    }
    set
    {
        if (string.IsNullOrWhiteSpace(value))
            TaxMode = null;
        else
            TaxMode = JsonConvert.DeserializeObject<TaxMode>(value);
    }
}

that solution will save your struct as JSON and use serialization to store and retrieve data to/from database.

Kamil Z
  • 181
  • 12