Jam*_*123 0 c# entity-framework linq-to-sql
我正在尝试使用 EF6 中的表名称读取实体属性及其类型。例如
public partial class ContextEntities : DbContext
{
public virtual DbSet<tblNote> tblNotes { get; set; }
}
public partial class tblNote
{
public int intNoteID { get; set; }
public string strLoanNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我有一个"tblNote"以字符串形式调用的实体名称。通过使用这个表名,我想获取tblNote实体及其属性和类型。
所以我这样做了
List<Reflection.PropertyInfo> props = new List<Reflection.PropertyInfo>();
PropertyInfo entityProperty = contextEntities.GetType().GetProperties().
Where(t => t.Name == "tblNote").Single();
if ((entityProperty != null))
props.Add(entityProperty);
Run Code Online (Sandbox Code Playgroud)
这是行不通的。我只是获得contextEntities属性。怎么做?
使用此查询:
var tblNoteProperties = contextEntities
.GetType()
.GetProperties()
.Where(p =>
p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.Select(p => p.PropertyType.GetGenericArguments()[0])
.Where(t => t.Name == "tblNote")
.SelectMany(t => t.GetProperties())
.ToArray();
Run Code Online (Sandbox Code Playgroud)
请注意,该模型可以动态构建,无需在派生类型DbSet<T>上声明属性DbContext。在这种情况下,您应该使用 EDM 来探索实体类型及其属性。
| 归档时间: |
|
| 查看次数: |
3763 次 |
| 最近记录: |