Entity Framework 6 DBContext with only a subset of all tables

强颜欢笑 提交于 2019-12-05 08:06:43
Taraman

what you trying to something like "Bounded Context" which is one of DDD patterns

So, you can check this article by Julie Lerman, Shrink EF Models with DDD Bounded Contexts

Simply just create your DBContext for your tables. To prevent Entity Framework moaning about the not mapped tables, you have switch off the db initialization in your application. Put this in your global.asax/Startup.cs

Database.SetInitializer<YourDbContext>(null);

It tells EF to stop comparing your actual DB structure against your DbContext. It also means that if someone changes your EF mapped tables, you have no chance of getting notified about that.

When you have a many-to-one relation between class A and class B:

public class A
{
   public B b {get; set;}
}
public class B
{
    public ICollection<A> As {get; set;} 
}

and define following DbContext, EF automatically includes DbSet<B> to the DbContext:

public class MyContext : DbContext
{
   ...
   public DbSet<A> As { get; set; }
}

So, if you want your light DbContext does not includes the related DbSets, simply use Ignore method:

public class MyContext : DbContext
{
   ...
   public DbSet<A> As { get; set; }

   protected override void OnModelCreating( DbModelBuilder modelBuilder )
   {
      modelBuilder.Ignore<B>();
   }
}

It looks like you used a tool like Entity Framework Power Tools to generate the entity classes and mappings. This would have generated a class for each table in the database, a huge context, mappings for all these classes and all possible associations. This is way too much.

First remove all classes and mappings that you don't need. Then remove all associations to removed classes in the few classes you have left, not the primitive foreign key fields. Also remove all DbSets from the context except the few you need.

This slimmed-down class model will be consistent in itself. It won't have associations to all entities in the database, but it will be possible to filter by foreign key values that refer to entities outside the context.

If you generated/created the code in any other way this is still the crux: only use navigation properties to other classes in the class model. For other references use primitive foreign key properties.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!