如何通过 PRESENTER 将数据从数据库传输到 VIEW?

How to transfer the data from Data Base to VIEW via PRESENTER?

我正在尝试创建使用 WinForms 实现 MVP 模式的应用程序。

其中我也在使用EF+CodeFirst+Linq。

VIEW上有DataGridView控件,需要填写数据。 VIEW 调用 PRESENTER class 的方法 SELECT(),后者又调用 SELECT() 的方法型号 class.

如何通过PRESENTER将数据从数据库传输到VIEW?

我正在尝试使用 return 但它不起作用,因为我正在使用 USING 块。

internal void Select()
{
    using (GoodsContext context = new GoodsContext())
    {
        var items = from Items in context.Goods
                    select Items;
    }
}

您应该将方法类型 Selectvoid 更改为 IEnumerable<Good> 以便能够 return 某些东西。还使用 .ToList 将结果具体化为 List:

internal IEnumerable<Good> Select()
{
    using (GoodsContext context = new GoodsContext())
    {
        var items = (from Items in context.Goods
                     select Items).ToList();
        return items;
    }
}

Select 方法的 return 类型更改为 List<Good>
然后 "materialize" result 到 List of data,你就不会依赖 DataContext

internal List<Good> Select()
{
    using (GoodsContext context = new GoodsContext())
    {
        return context.Goods.Select(items => items).ToList();
    }
}

很有趣的问题。当然可以将查询 return 实现为 IEnumerable,但我想知道如何将其 return 实现为 IQueryable,以允许进一步 filtering/sorting 等。我看到的唯一方法是 not 处理 DbContext (显然 returned 查询保持引用它),但它安全吗?然后我用谷歌搜索并找到了这个 Do I always have to call Dispose() on my DbContext objects? Nope。里面的解释对我来说听起来很合理,我们已经有了一个我们不应该Dispose的一次性对象(Task)。

很快,您可以删除 using 语句和 return IQueryable