databind entityframework ObjectSet <t>到gridcontrol(c#)</t>

时间:2013-03-06 08:44:11

标签: c# winforms entity-framework-4 devexpress xtragrid

我使用DevExpress EntityInstantFeedbackSource作为XtraGrid控件的数据源。但是我没有使用app.config文件中的连接字符串;而是我在运行时设置实体框架的连接字符串 代码如下:

void Form1_Load(object sender, EventArgs e)
{
    entityInstantFeedbackSource1.KeyExpression = "Prodid";
    entityInstantFeedbackSource1.GetQueryable += entityInstantFeedbackSource1_GetQueryable;
    entityInstantFeedbackSource1.DismissQueryable += entityInstantFeedbackSource1_DismissQueryable;
    gridControl1.DataSource = null;
    gridControl1.DataSource = entityInstantFeedbackSource1;
}
void entityInstantFeedbackSource1_GetQueryable(object sender, GetQueryableEventArgs e)
{
    EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
    ecsb.Metadata = @"res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl";
    ecsb.Provider = @"System.Data.SqlClient";
    ecsb.ProviderConnectionString = @"data source=.\sqlexpress;initial catalog=AdventureWorks;  integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
    using (var context = new ObjectContext(ecsb.ConnectionString))
    {
        context.DefaultContainerName = "AdventureWorksEntities";
        ObjectSet<Person> query = context.CreateObjectSet<Person>();
        var q = from s in query
               select s;
        e.QueryableSource = q;
        e.Tag = context;
    }
}

void entityInstantFeedbackSource1_DismissQueryable(object sender, GetQueryableEventArgs   e)
{
    ((ObjectContext)e.Tag).Dispose();
}

网格是空白的。但是,如果我围绕'query'编写foreach循环并在Console.WriteLine中查看输出,那么我可以看到数据。
此外,如果我设置e.QueryableSource = q.ToArray().AsQueryable(),那么我可以在网格中看到数据。但这样做会使EntityInstantFeedbackSource的好处无效,从而一次加载所有数据。

为什么查询中没有数据?以及如何将ObjectSet数据绑定到gridcontrol?

1 个答案:

答案 0 :(得分:1)

我认为此问题的原因是您将ObjectContext直接置于GetQueryable处理程序中,而不是仅在DismissQueryable中执行此操作。此外,您可以将生成的对象集直接传递给e.QuerableSource 因此,正确的代码应如下所示:

void entityInstantFeedbackSource_GetQueryable(object sender, DevExpress.Data.Linq.GetQueryableEventArgs e) {
    //... connection initialization ...
    var context = new ObjectContext(ecsb.ConnectionString);
    ObjectSet<Person> personSet = context.CreateObjectSet<Person>();
    e.QueryableSource = personSet;
    e.Tag = context;
}
void entityInstantFeedbackSource_DismissQueryable(object sender, DevExpress.Data.Linq.GetQueryableEventArgs e) {
    ((ObjectContext)e.Tag).Dispose();
}