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

前端 未结 3 554
春和景丽
春和景丽 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: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
    {
        get
        {
            if ((this._Customers == null))
            {
                this._Customers = base.CreateQuery("[Customers]");
            }
            return this._Customers;
        }
    }
    
    private global::System.Data.Objects.ObjectQuery _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 GetEntities()
    {
        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(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(es.Name);
    }
    

提交回复
热议问题