【问题标题】:Accessing the DBContext from within an EF CodeFirst Model instance从 EF CodeFirst 模型实例中访问 DBContext
【发布时间】:2012-12-10 20:19:04
【问题描述】:

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

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

基本上,我想知道如何在下面实现 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...);
    }

    /* ... */
}

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

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

    首先,您不需要 DbContext 来执行此操作,我假设 Discussion.Id 是 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; }
    
        ...
    }
    

    这应该允许您根据猴子表中讨论字段中的值引用一组过滤的猴子。

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

    【讨论】:

    • 假设我想对代码中的成员进行任意过滤......基本上,我无法将一整套复杂的约束表达为 SQL,所以我想使用 C#做一个SQL查询,然后对结果做一堆处理......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多