Efcore: Support collections of scalar types

Created on 26 Dec 2015  路  7Comments  路  Source: dotnet/efcore

An entity class with a property of List or ICollection of Int does not work.

c# public class Foo { public ICollection<int> RowValues { get; set; } public ICollection<int> ColValues { get; set; } }

Here is the error message.
The property 'RowValues' on entity type 'Models.Foo' has not been added to the model or ignored.

Is this a bug or am I doing this wrong?

Thanks

type-enhancement

Most helpful comment

@Soundman32 Can you show the proposed API to configure it or submit a draft PR?

All 7 comments

EF doesn't support storing collections of scalar types. The best workaround at the moment would be to add [NotMapped] to those properties and then have another property that wraps the ICollection<int> represents the serialized for of the data (such a comma-separated string). Then let EF map to that property.

Any tips on how I could configure EF Core to always map IEnumerable<int> to string and the value stored to DB will be its JSON representation?

I.e. custom mapping, serializing and parsing based on type (that is, general - not based on property per se).

Note: there are two potential approaches to solving this problem:

  • Using a value converter to serialize all the values into a single column
  • Mapping to a table which contains the values and collapsing that mapping down to the IEnumerable/ICollection property on the entity. (See #14115)

We may choose to implement either one or both of these. The first can be done manually without mich code using a custom value converter. For example:

C# modelBuilder .Entity<User>() .Property(e => e.Roles) .HasConversion( v => string.Join(',', v), v => v.Split(',', StringSplitOptions.None));
(Note that this is a naive serialization that doesn't account for the separator character being included in some of the values, but using something more robust, such as JSON serialization, is just a matter of plugging in the right serialization code.)

@ajcvickers - Trying to understand if this is good first issue?

@smitpatel I don't think it is--looks like it just got this due to being up-for-grabs in 2015.

I have a proof of concept for this that works on owned types but it's only for the Cosmos driver. The only thing preventing me from creating a PR is a small issue with deserialising the collection (at the moment, you need a single function call to 'fixup' things, that obviously I need to get around).

@Soundman32 Can you show the proposed API to configure it or submit a draft PR?

Was this page helpful?
0 / 5 - 0 ratings