简体   繁体   中英

How can I store an Array of Ints in my database, in a single field, using Code First Entity Framework?

What I want to do is store an Array of Ints in my database. I am Using Code First Entity Framework to create my database I can't seem to create a List or Array element in the database. The List item doesn't create a field. I gather that this is because it would need a separate table.

What is the best way to store my array in a single field here. Should I convert the array to a String, or is there an easier way?

My model contains:

public string Title { get; set; }
public List<int> IdArray { get; set; }

NHibernate supports this, but EF doesn't.

If you need to do it the only option is to store it serialized. For example you can do:

  • a XML column, and store it serialzed as XML
  • a char column, and store it serialized as JSON

EF will not automatically serialize / deserialize it. You should add a property that does the serialization/deserialization for you

public string IdsColumn { get; set; } // Mapped to DB

[NotMapped]
public List<int> Ids
{
    get { return Deserialize(IdsColumn); }
    set { IdsColumn = Serialize(value); }
}

Of course you have to provide the serialization functions implementation, using XMLSerializer or JSON.NET, for example.

If you want this functionality implemented, look here: EF data user voice

For example Richer collection support, including ordered collections and dictionaries of value types

You can vote for it.

Im not too sure of your situation but Most of the time this is never necessary...

Basically if you arrive at such a situation you should look at normalizing your table further. data in tables need to be "atomic". once retrieved as objects it can be in a list.

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