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

时间:2015-09-22 00:41:35

标签: c# entity-framework

我有DB上下文和实体类定义如下:

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类的属性?谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢大家。解决方案如下:

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