实体框架CTP4代码第一:映射保护属性 [英] Entity Framework CTP4 Code First: Mapping protected properties

查看:130
本文介绍了实体框架CTP4代码第一:映射保护属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模型上使用一个惰性加载集合,但是我想通过单独的方法来完成添加/删除功能。所以这样的东西:

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);
  }
}

我不知道如何配置映射为了这。我研究了使用一个配置类:EntityConfiguration。但是由于该属性受到保护,我无法弄清楚如何设置配置。有没有办法完成我在这里做的工作?

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?

推荐答案

您可以使用readonly static Expression访问受保护的这样的财产

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();
}

在DbContext类中的OnModelCreating方法中使用它来映射protected属性

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);
}

这篇关于实体框架CTP4代码第一:映射保护属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆