mar*_*cob 8 .net c# entity-framework
我正在寻找DataContext.GetTable<TEntity>实体框架中的等价物.我找到了这个ObjectContext.CreateQuery<T>方法,但它有所不同,DataContext.GetTable<TEntity>因为它需要一个查询字符串才能工作.
有没有办法在不指定查询字符串的情况下使用实体类型为表获取IQueryable对象?
*EDIT: Added code snippet*
这是我实现的与linq2sql一起使用的Repository类的片段.我不能使用, ObjectContext.[TableName]因为它不再是通用的.
public class BaseRepository<TClass> : IDisposable
where TClass : class
{
protected BaseRepository(DataContext database)
{
_database = database;
}
...
public IQueryable<TClass> GetAllEntities()
{
IQueryable<TClass> entities = _database.GetTable<TClass>();
return entities;
}
public IQueryable<TClass> GetEntities(Expression<Func<TClass, bool>> condition)
{
IQueryable<TClass> table = _database.GetTable<TClass>();
return table.Where(condition);
}
Run Code Online (Sandbox Code Playgroud)
*EDIT: Added my solution (so far..)*
这就是我正在使用的:
public IQueryable<TClass> GetEntities(Expression<Func<TClass, bool>> condition)
{
IQueryable<TClass> table = _database.CreateQuery<TClass>(typeof(TClass).Name);
return table.Where(condition);
}
Run Code Online (Sandbox Code Playgroud)
只要类名与表名相同,这就可以工作.当我开始为同一个表使用不同的对象时,这将成为我的问题.
我希望我已经清楚了,先谢谢,
Marco :)
实际上,EF设计者本身使用CreateQuery硬编码字符串作为静态参考.如果你深入了解设计器文件,你会看到这样的东西:
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;
Run Code Online (Sandbox Code Playgroud)
从技术上讲,没有完美的解决方案,因为您可以为不同的实体集使用相同的实体类型.但你可以给它旧的大学尝试:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9705 次 |
| 最近记录: |