Csharp/C#教程:entity framework是否具有来自Linq2Sql(ObjectContext.CreateQuery ?)的等效DataContext.GetTable分享


entity framework是否具有来自Linq2Sql(ObjectContext.CreateQuery ?)的等效DataContext.GetTable

我正在寻找entity framework中的DataContext.GetTable的等价物。 我找到了ObjectContext.CreateQuery方法,但它与DataContext.GetTable不同,因为它需要一个查询字符串才能工作。

有没有办法在不指定查询字符串的情况下使用实体类型为表获取IQueryable对象?

*EDIT: Added code snippet*
这是我实现的与linq2sql一起使用的Repository类的片段。 我不能使用ObjectContext.[TableName]因为它不再是通用的。

 public class BaseRepository : IDisposable where TClass : class { protected BaseRepository(DataContext database) { _database = database; } ... public IQueryable GetAllEntities() { IQueryable entities = _database.GetTable(); return entities; } public IQueryable GetEntities(Expression<Func> condition) { IQueryable table = _database.GetTable(); return table.Where(condition); } 

*EDIT: Added my solution (so far..)*
这就是我正在使用的:

 public IQueryable GetEntities(Expression<Func> condition) { IQueryable table = _database.CreateQuery(typeof(TClass).Name); return table.Where(condition); } 

只要类名与表名相同,这就可以工作。 当我开始为同一个表使用不同的对象时,这将成为我的问题。

我希望我已经清楚了,先谢谢,
马可:)

实际上,EF设计者本身使用带有硬编码字符串的CreateQuery作为静态引用。 如果你深入了解设计器文件,你会看到这样的东西:

 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; 

从技术上讲,没有完美的解决方案,因为您可以为不同的实体集使用相同的实体类型。 但你可以给它旧的大学尝试:

 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); } 

 public IQueryable GetTable(T entity) where T : class { return context.CreateObjectSet(); } 

我希望我不会错过这一点,但不会是:

 ObjectContext.TableName 

其中TableName是您要使用的类型的EntitySet。

上述就是C#学习教程:entity framework是否具有来自Linq2Sql(ObjectContext.CreateQuery ?)的等效DataContext.GetTable分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/992076.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐