Reputation: 6494
I'm trying to create "some kind" of custom "DbContext" for very specific application which uses MongoDb. And I faced with one problem:
How did DbSet know of DbContext existence?
I mean, when I write
public DbSet<Assignment> Assignments { get; set; }
public DbSet<User> Users { get; set; }
in my DbContext, how the DbSet instance gets the reference to the DbContext class? Via reflection?
But when I was digging into EntityFramework source code I faced another problem
public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class => _setInitializer.Value.CreateSet<TEntity>(this);
In this expression I cannot understand what does lambda expression in "where" clause. Could someone enlighten me?
UPD
Every time when I call my DbSet property in DbContext
public class BlogPostContextContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
The DbSet calls the DbContext and it produces necessary manipulations over the data. My question is: how DbSet gets the reference to the DbContext. I'm asking about underlying communication between DbSet and DbContext.
Thanks in advance.
Excuse my english.
Ivan Talalaev
Upvotes: 1
Views: 595
Reputation: 149518
I cannot understand what does lambda expression in "where" clause.
The method declaration has two parts. The first is a generic type constraint:
where TEntity : class
This means that any type used in the place of TEntity
needs to be a reference type.
The second part is an Expression-bodied function:
=> _setInitializer.Value.CreateSet<TEntity>(this);
Which is a C# 6.0 feature. If your method is a one-liner, it can be declared like a Lambda Expression. It simply means that each time you call Set
, it will invoke the one line "body" of the method. The compiler will turn it into a named method "behind the scenes".
How did DbSet know of DbContext existence?
It doesn't know about it directly. DbContext
represents your database, DbSet
represents a table in that database. When you're manipulating your DbSet
, it implicitly holds a reference to it's underlying DbContext
and adds it's entities via the context.
Upvotes: 3
Reputation: 6494
I found an answer for my last part of question.
According to this and this EntityFramework 6 (not sure about new EF7)
DbSet keep reference _context
to the DbContext and uses it to Add or Remove entities.
In turn DbContext some how (possibly via reflection) sets that references _context
in all its encapsulated fields of type DbSet at time of cunstructor call.
Upvotes: 0