是否可以在DataGridView中显示联接的查询?

时间:2018-11-16 21:51:28

标签: c# entity-framework

我有一个Entity Framework应用程序,我需要将BindingSource的DataSource属性设置为联接查询的结果,如下所示:

var joined = _context.Products.Join(_context.Categories, p=>p.CategoryId, c=>c.CategoryId, (product, category) => new
        {
            ProductName = product.Name,
            CategoryName = category.Name
        });

这是否可行,还是DataSources必须等于DbSet <> s? 例如,这有效:

this.supplierBindingSource.DataSource = _context.Suppliers.Local.ToBindingList();

关于, 胡安

2 个答案:

答案 0 :(得分:0)

我相信您希望为联接的结果创建一个类,并实例化如下:

    class ProductCategory
    {
        string ProductName { get; set; }
        string CategoryName { get; set; }
    }

    private void test()
    {
        var joined = _context.Products.Join(_context.Categories, p => p.CategoryId, c => c.CategoryId, (product, category) => new ProductCategory
        {
            ProductName = product.Name,
            CategoryName = category.Name
        });
    }

答案 1 :(得分:0)

最终的解决方案是:

var theList = joined.ToList();
var bindList = new BindingList<ProductCategory>(theList);
this.dataGridView4.DataSource = bindList;

这行得通!