I\'m looking for an equivalent of the DataContext.GetTable
in Entity Framework.
I\'ve found the ObjectContext.CreateQuery
m
public IQueryable GetTable<T>(T entity) where T : class
{
return context.CreateObjectSet<T>();
}
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.
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);
}