使用EF5绑定到数据网格视图问题

时间:2013-07-25 14:33:21

标签: c# winforms entity-framework

我是使用EF的新手,我目前正在使用EF5尝试将数据从视图绑定到WinForms应用程序中的数据网格视图。我不确定如何正确地做到这一点,我收到了一个错误:

不支持直接与商店查询(DbSet,DbQuery,DbSqlQuery)绑定数据。而是使用数据填充DbSet,例如通过在DbSet上调用Load,然后绑定到本地数据。对于WPF绑定到DbSet.Local。对于WinForms绑定到DbSet.Local.ToBindingList()。

这是我的代码:

using (MyEntities context = new MyEntities ())
        {

            var qry = from col in context.vwSystemProperties
                      select new
                          {
                              SystemPropertyName = col.SystemPropertyName,
                              SystemPropertyEnumVal = col.SystemPropertyEnumVal,
                              SystemPropertyValue = col.SystemPropertyValue,
                              ApplicationScope = col.ApplicationScope,
                              CategoryScope = col.CategoryScope,
                              EntityScope = col.EntityScope,
                              VersionDate = col.VersionDate,
                              VersionUser = col.VersionUser
                          };


            BindingSource bs = new BindingSource();
            bs.DataSource = qry;
            SystemPropertyDGV.DataSource = bs;

        }

我认为我完全不明白错误指示我做什么。我做了一些简短的搜索,但我认为我没有找到我需要的东西。 DbSet应该如何实现并用于将数据绑定到DGV,还是有更简单的方法?

可以让我对如何将qry对象正确绑定到数据网格视图提供一些见解吗?现在我只需要查看数据,但是我希望能够访问一行并根据ID更新它。

由于

1 个答案:

答案 0 :(得分:1)

只需对返回的查询使用ToList()方法。

尝试以下方法:

using (MyEntities context = new MyEntities ())
{

    var qry = from col in context.vwSystemProperties
              select new
                  {
                      SystemPropertyName = col.SystemPropertyName,
                      SystemPropertyEnumVal = col.SystemPropertyEnumVal,
                      SystemPropertyValue = col.SystemPropertyValue,
                      ApplicationScope = col.ApplicationScope,
                      CategoryScope = col.CategoryScope,
                      EntityScope = col.EntityScope,
                      VersionDate = col.VersionDate,
                      VersionUser = col.VersionUser
                  };


    BindingSource bs = new BindingSource();
    bs.DataSource = qry.ToList();
    SystemPropertyDGV.DataSource = bs;

}
相关问题