考虑以下实体:
public partial class User
{
public virtual long Id { get; set; }
public virtual string Email { get; set; }
public virtual long DepartmentId { get; set; }
public virtual Department Department{ get; set; }
}
public partial class Department
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
protected override void OnModelCreating (DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>();
modelBuilder.Entity<User>().HasKey<long>(p => p.Id);
modelBuilder.Entity<User>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<User>().Property(p => p.Email).IsRequired().IsMaxLength();
modelBuilder.Entity<Department>();
modelBuilder.Entity<Department>().HasKey<long>(p => p.Id);
modelBuilder.Entity<Department>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Department>().Property(p => p.Name).IsRequired().HasMaxLength(256);
}
我故意跳过上面的关系映射,因为它与问题无关。
我正在基于这些手写实体生成DTO和MVC模型,并希望以编程方式访问OnModelCreating
方法中定义的属性配置。
我确实记得有一种方法可以使用DbContext对象访问模型/模式,但是没有找到在各种搜索中实现上述方法的方法。任何指针都会受到赞赏。
更新:在添加下面答案中建议的代码后,我收到了一个奇怪的例外情况,但搜索一直是徒劳的。
Error 2 Running transformation: System.EntryPointNotFoundException: Entry point was not found.
at System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()
at Microsoft.VisualStudio.TextTemplating4060E50565D24E6D60BA3E80DDCE2A21E9485A5F4982CD591645549489576DC7687B06DE6C675CAA51175F177B32340E9E07C1C8B0487B2BD65D022D75892D00.GeneratedTextTransformation.TransformText()
答案 0 :(得分:0)
我认为你想要的是元数据工作区:
var db = new YourDbContext();
var oc = ((IObjectContextAdapter)db).ObjectContext;
var mw = oc.MetadataWorkspace;
然后您可以通过它访问模型。例如,您可以获取所有实体的名称:
var entities = mw.GetItems<EntityType>(DataSpace.OSpace);
foreach (var entity in entities)
Console.WriteLine(entity.Name);