Does the Entity Framework have an equivalent of DataContext.GetTable from Linq2Sql (ObjectContext.CreateQuery?)

前端 未结 3 541
春和景丽
春和景丽 2021-01-05 00:25

I\'m looking for an equivalent of the DataContext.GetTable in Entity Framework. I\'ve found the ObjectContext.CreateQuery m

相关标签:
3条回答
  • 2021-01-05 01:06
    public IQueryable GetTable<T>(T entity) where T : class
    {
        return context.CreateObjectSet<T>();
    }
    
    0 讨论(0)
  • 2021-01-05 01:11

    I hope I'm not missing the point, but wouldn't it be:

    ObjectContext.TableName
    

    Where TableName is the EntitySet of the type you want to work with.

    0 讨论(0)
  • 2021-01-05 01:19

    Actually, the EF designer itself uses CreateQuery with hard-coded strings for the static references. If you dig into the designer file you'll see something like this:

    public global::System.Data.Objects.ObjectQuery<Customers> Customers
    {
        get
        {
            if ((this._Customers == null))
            {
                this._Customers = base.CreateQuery<Customers>("[Customers]");
            }
            return this._Customers;
        }
    }
    
    private global::System.Data.Objects.ObjectQuery<Customers> _Customers;
    

    Technically there's no perfect solution because you can use the same entity type for different entity sets. But you can give it the old college try:

    public IQueryable<TEntity> GetEntities<TEntity>()
    {
        Type t = typeof(TEntity);
        var edmAttr = (EdmEntityTypeAttribute)Attribute.GetCustomAttribute(t,
            typeof(EdmEntityTypeAttribute), false);
        if (edmAttr == null)  // Fall back to the naive way
        {
            return context.CreateQuery<TEntity>(t.Name);
        }
        var ec = context.MetadataWorkspace.GetEntityContainer(
            context.DefaultContainerName, DataSpace.CSpace);
        var entityType = context.MetadataWorkspace.GetType(edmAttr.Name,
            edmAttr.NamespaceName, DataSpace.CSpace);
        var es = ec.BaseEntitySets.First(es => es.ElementType == entityType);
        return context.CreateQuery<TEntity>(es.Name);
    }
    
    0 讨论(0)
提交回复
热议问题