繁体   English   中英

如何在运行时在Entity Framework Code First中获取实体类的属性

[英]How to get the properties of entity class in Entity Framework Code First at runtime

我的数据库上下文和实体类定义如下:

public class DBContext : DbContext
{
    public DBContext()
        : base("name=DbConnectionString")
    { }

    public virtual DbSet<Foo> Foos { get; set; }
}

public class Foo
{
    [Key]
    public long FooID { get; set; }
    public string Bar1 { get; set; }
    public string Bar2 { get; set; }
}

我正在尝试在运行时获取类Foo的属性。 我试过反射:

DBContext db = new DBContext(dbConnString);
db.Database.CreateIfNotExists();
List<PropertyInfo> properties = db.Foos.GetType().GetProperties();

此代码无法编译。 我如何获得Foo类的属性? 谢谢!

感谢大家。 解决方法如下:

DBContext db = new DBContext(dbConnString);
db.Database.CreateIfNotExists();
PropertyInfo[] properties = typeof(Foos).GetProperties();
foreach (var prop in properties)
{
    process(prop.Name);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM