Freshblood
Freshblood

Reputation: 6431

Entity aware of his DbContext?

I found some restrictions in POCO class approach in entity framework because entities can no process related queries by itself without holding DbContext reference. I guess that proxies holding reference to it privately and we have no access it. The thing i want to achieve is at below model hold Followers but if i need count of Followers instead of Followers so i can't do this by model because model has no reference to context. So solution is hold FollowersCount not mapped property on model and execute query for it in repository then set it. This looks like creating DTO object without creating new DTO.

Second approach can be holding DbContext reference again explicitly in model properties as not mapped then execute related queries.

Downside of both approach is repeatedly setting values in every fetched models manually. What do you think both solutions ? Is there better approach ?

public class Post : Entity
{
    public string Title { get; set; }
    [NotMapped]
    public DbContext Context { get; set; }
    public virtual List<User> Followers{ get; set; }
    public virtual FollowersCount()
    {
        return //use DbContext and just execute query for count of Followers
    }
}

Upvotes: 0

Views: 477

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

That idea is breaking separation of concerns quite heavily. You will make your entity dependent on EF = you will mess your domain model with data access code. If you want to use ORM correctly approach the problem in ORM way. If you need the count of followers you have two choices:

  • Load followers and use simple collection's Count - that is doamin way done by entity
  • Ask data access layer for count - that is data access way done by data access layer

The point of domain model is to work on loaded objects not to query database, that is the point of data access layer (repositories, EF, data access objects, etc.). If you need to get count of followers without loading them use:

int count = context.Entry(post)
                   .Collection(p => p.Followers)
                   .Query()
                   .Count();

Upvotes: 4

Related Questions