0

我使用 DevExpressEntityInstantFeedbackSource作为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();
}

网格是空白的。但是,如果我围绕“查询”编写一个 foreach 循环并查看输出,Console.WriteLine那么我可以看到数据。
另外,如果我设置e.QueryableSource = q.ToArray().AsQueryable()了,那么我可以在网格中看到数据。但是这样做会通过抵消EntityInstantFeedbackSource.

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

4

1 回答 1

1

I believe the reason of this issue is that you are disposing the ObjectContext directly in GetQueryable handler rather then to do it in DismissQueryable only. Moreover you can pass the resulting object set directly to e.QuerableSource.
Thus the correct code should looks like this:

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();
}
于 2013-03-07T07:57:22.730 回答