Search code examples
c#entity-frameworkentity-framework-6.1

EF Fluent Mapping - map a collection field from another table


This may already have been asked somewhere, but I can't find a question exactly matching what I'm trying to do.

At the database level, I have TableB which has only two fields - a foreign key to TableA and a nvarchar(max) Code field. The relationship from TableA to TableB is one-to-many.

At the EF level, I would like to skip mapping TableB at all. TableA would look like this:

public class TableA
{
    public ICollection<string> BCodes {get; set;}
}

I would like BCodes to be populated from the Code field of all of the related TableB entities. I know I could accomplish this using views and other hacks on the database, but that destroys the separation of concerns. Is this possible using EF, or do I have to map a TableB entity with just the one string property?

Update I should clarify that this can be a read-only collection for my specific case. Other people who stumble across this question may have different needs, so if you have ideas of a read/write way to implement it, that would be great too.


Solution

  • At least up to EF 6.1, it's not possible to define primitive type collections (for example a collection of strings). It must be done indirectly.

    The best approach I've ever seen is this SO answer.

    Alternatively you could use NHibernate, that support this functionality. For example, you can see this SO question.