获取EntityFramework已添加实体作为gridview数据源

时间:2013-08-06 16:47:05

标签: gridview entity-framework-4

在EntityFramework 4中,这是从中获取实体的正确方法:
- 数据库(减去已删除的对象),
- 和记忆中添加的内容
在GridView中显示它们

将linq用于实体我获取当前数据库中的数据 使用ObjectStateManager.GetObjectStateEntries(entityState).Select(ent => ent.Entity).OfType<IEntityWithKey>(),我得到已添加和/或已删除(根据需要)

使用linq到实体我在查询结果中得到Deleted对象,所以它们显示在gridvew(以及Modified和Unchanged)中,但这不是我想要的,我不想要删除了对象。

我需要的是在gridview中显示当前数据库中除Deleted对象外的所有数据,以及内存中添加的objets。 (所有这一切都在调用Savechanges之前)。

我在BL类中有一个方法,它返回一个类型化的集合并用它设置gridview数据源 为此,我做了:
- 一个linq到实体来检索db数据(比如Collection1),
- GetObjectStateEntries(已删除)以获取已删除的实体(Collection2),
- GetObjectStateEntries(已添加)以获取新的内存添加(Collection3)

然后迭代Collection1.ToList()以删除Collection2中的项目,然后使用Collection3删除联盟。

它有效,但我不喜欢它。

有没有更好/更合适的方法呢?有任何帮助/建议吗?

提前完成。

这是一些代码 获取数据库实体的方法(此处包含已删除的对象):

public IEnumerable<ConnectorTransformationLookUpConceptData> GetConnectorTransformationLookUpConceptsView(int idConnectorTransformation)
    {
    var data = from r in Entities.ConnectorTransformationLookUpConcept
               join c in Entities.LookUpConcept on r.IdLookUpConcept equals c.IdLookUpConcept
               ....

    return ExcludeDeleted(data).Union(AddedData(idConnectorTransformation)).OrderBy(e => e.Concept);
    }

删除已删除对象的方法(在上一次返回中调用):

private List<ConnectorTransformationLookUpConceptData> ExcludeDeleted(IEnumerable<ConnectorTransformationLookUpConceptData> collection)
    {
        List<ConnectorTransformationLookUpConceptData> l = collection.ToList();
        var deleted = GetDeletedEntities<ConnectorTransformationLookUpConcept>();

        foreach (ConnectorTransformationLookUpConcept d in deleted)
        {
            ConnectorTransformationLookUpConceptData o = l.Find(c => c.idConnTransf == d.IdConnectorTransformation && c.idLooUpConcept == d.IdLookUpConcept);
            if (o != null) l.Remove(o);
        }

        return l;
    }

最后由“AddedData”和“GetDeletedEntities”调用最终调用的方法,该调用返回所需的对象(在EntityState.Added或EntityState.Deleted中)

protected IEnumerable<IEntityWithKey> GetEntities<IEntityWithKey>(EntityState entityState)
    {
        IEnumerable<IEntityWithKey> data =
        this.Entities.ObjectStateManager.
            GetObjectStateEntries(entityState).
            Select(ent => ent.Entity).
            OfType<IEntityWithKey>();
        return data;
    }

0 个答案:

没有答案
相关问题