1

I have an object, say the usual Order that have a collection of LineItem. To satisfy some business rules I need to have complete control against the list (i.e. nobody can add an element to this list simply using the built in Add() method). So I do something like:

public class Order {
    private List<LineItem> lineItems {get; set;} 

    public IEnumerable<LineItem> LineItems {
        get { return lineItems.AsReadOnly(); }
    }
}

This solution do the job but have a big side effects if other player come into play (e.g. Entity Framework). In fact during the model building, EF expects an ICollection (while I need an IEnumerable):

modelBuilder.Entity<Order>()
            .HasMany<LineItem>(e => e.LineItems) // here is the exception: No implicit conversion among IEnumerable and ICollection
            .OtherMappingProperties(); // <-- this don't belong to EF's Fluent API :)

EDIT 1 - The solution provided by @Pieter21 avoid the compile time error, since LineItem is now a Colection, but I get a runtime exception when somewhere in my code I have something like:

return Set.Include(s => s.LineItems)

since none have set lineItems (none could since is private) so I get a NullPointerException. Since the Entity configuration and Domain model are in different package the use of internal instead of private would not resolve the problem unless the use of InternalsVisibleTo (but I don't want to spoil the AssemblyInfo.cs of the Domain model with something persistence related)

How to workaround this issue?

PS: The EF configurations and domain model are in different namespaces.

BAD_SEED
  • 4,840
  • 11
  • 53
  • 110
  • possible duplicate of [Entity Framework read only collections](http://stackoverflow.com/questions/11191103/entity-framework-read-only-collections) – Gert Arnold Sep 16 '14 at 09:23

1 Answers1

0

Can you do something like:

        public ICollection<LineItem> LineItems 
        {
            get 
            { 
                return new ReadOnlyCollection<LineItem>(lineItems); 
            } 
        }
BAD_SEED
  • 4,840
  • 11
  • 53
  • 110
Pieter21
  • 1,765
  • 1
  • 10
  • 22