5

I would like to use a lazy-loading collection on a model, but I want Add/Remove functionality to be done through separate methods. So something like this:

class Model
{
  protected virtual ICollection<Something> _somethings { get; set; }

  public IEnumerable<Something> Somethings 
  { 
    get { return _somethings; } 
  }

  public void AddSomething(Something thingToAdd)
  {
    /*  logic */
    _somethings.Add(thingToAdd);
  }
}

I can't figure out how to configure the mapping for this. I looked into using a configuration class: EntityConfiguration. But since the property is protected I can't figure out how to set a configuration on it. Is there any way to accomplish what I'm trying to do here?

zrg
  • 4,247
  • 3
  • 17
  • 11

3 Answers3

1

You can use readonly static Expression for access to protected property like this

protected virtual ICollection<Something> _somesing { get; set; }
public static readonly Expression<Func<Model, ICollection<Something>>> Expression = p => p._something;

public IReadOnlyCollection<Something> Something
{
     return _sumething.AsReadOnly();
}

And use it in OnModelCreating method in DbContext class for mapping protected property

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>().HasMany<Something>(Model.Expression);
}
Almeonamy
  • 23
  • 9
0

Ive heard this only can be done using EDMX file way.. not code first.

Rushino
  • 9,415
  • 16
  • 53
  • 93
0

I suppose if you declare the configuration class (inheriting EntityConfiguration) inside your Model class, it could work. It's not a nice solution, since subclassing is generally discouraged, but it's the only thing I can think of.