简体   繁体   中英

Work-around for Struct with Entity Framework, Code-First approach

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.

Structs are not supported.

You have to use class istead of it.

Updated

take a look at this Ladislav Mrnka answer

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM