I'm a little bit confused. Until today I thought that every table (used by EF) must be specified in DbContext class. But it looks like I need ONLY one! really?
Let me explain, Here's my DbContext:
public class MyDbContext : DbContext { public MyDbContext() : base("name=MyDbContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<MyDbContext>(null); base.OnModelCreating(modelBuilder); } public DbSet<Table1> Table1 { get; set; } public DbSet<Table2> Table2 { get; set; } public DbSet<Table3> Table3 { get; set; } public DbSet<Table4> Table4 { get; set; } public DbSet<Table5> Table5 { get; set; } } Here are two sample tables, connected 1:many
[Table("Table1")] public class Table1 { [Key] [Column("Table1Id", TypeName = "uniqueidentifier")] public int Table1Id { get; set; } [Column("Table2Id", TypeName = "int")] public int Table2Id { get; set; } [ForeignKey("Table2Id")] public Table2 Table2 { get; set; } } [Table("Table2")] public class Table2 { public Table2() { this.Table1s = new HashSet<Table1>(); } [Key] [Column("Table2Id", TypeName = "int")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Table2Id { get; set; } public ICollection<Table1> Table1s { get; set; } } Easy. Now, I want to query all Table2s with corresponding Table1s. I do:
var tables2 = fni.Set<Table2>() .Include(i => i.Table1s) .Where(t => t.Table2Id == 123456).ToList(); It all works, but I was shocked, when I discovered by accident, that it works even with this DbContext:
public class MyDbContext : DbContext { public MyDbContext() : base("name=MyDbContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<MyDbContext>(null); base.OnModelCreating(modelBuilder); } public DbSet<Table1> Table1 { get; set; } } or this..
public class MyDbContext : DbContext { public MyDbContext() : base("name=MyDbContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<MyDbContext>(null); base.OnModelCreating(modelBuilder); } public DbSet<Table2> Table2 { get; set; } } Can you explain to me, why does it work?
EDIT. It's not include. I was able to do:
var tables2 = fni.Set<Table2>() .Where(t => t.Table2Id == 123456).ToList(); having only this: public DbSet<Table1> Table1 { get; set; } in DbContext. It's not even Table2! They are connected via FK (definitions didn't change). So that would mean, that you must have only one table from one "chain" of tables. Is that correct?
Includeis not necessary. I edited my questioninclude, correct? Does it mean, that if your tables are connected viaForeignKeyattribute, you need to declare ONLY ONE table from that chain in DbContext?