从EF CodeFirst Model实例中访问DBContext

时间:2011-11-17 20:04:04

标签: entity-framework ef-code-first

我有一个名为Discussion的EF4.1 CodeFirst Model实例。

我想知道默认的“集合属性访问器”(例如下面的Discussion.messages.get)如何获得管理当前对象的数据库上下文,因为我想编写以相同方式工作的自定义访问器。

基本上,我想知道如何在以下实现 this.GET_MANAGING_DB_CONTEXT()

public class Discussion {

    // The default get; accessor seems to have access to the DBContext
    public virtual ICollection<Message> messages { get; set; }

    // How do I get access to the managing db context myself?
    public ICollection<Monkey> monkeys {
        get {
            return new List<Monkey>(from m in this.GET_MANAGING_DB_CONTEXT().Monkeys select m where m.discussion == this.ID));
        }
    }

    // Here's what I'm forced to do now, which requires passing DBContext around
    // everywhere the object is used, breaking encapsulation of data storage
    public ICollection<Monkey> monkeys(DBContext db) {
        return new List<Monkey>(from m in db.Monkeys...);
    }

    /* ... */
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否100%理解您的问题,但您似乎要求根据当前对象的主键设置一组过滤的Monkeys。

首先你不应该需要DbContext来做这个,讨论。我假设是一个PK值,而Monkey.discussion是一个FK值。

在codefirst中我希望你能做到这一点

public class Discussion {

    public Discussion()
    {
        monkeys = new List<Monkey>();
    }

    ...

    [InverseProperty("discussion")]
    public ICollection<Monkey> monkeys { get; set; }

    ...
}

public class Monkey
{
    ...

    [InverseProperty("monkeys")]
    public Discussion discussion { get; set; }

    ...
}

这应该允许您根据monkey表中讨论字段中的值引用过滤的Monkey集。

如果您仍需要访问讨论栏的值,请查看以下答案:Influencing foreign key column naming in EF code first (CTP5)