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.