virtual bool hasVoted from virtual Votes property

I don't exactly know how i should do it, but i know what i want to do.

I have a model

     Id:Guid (PK)
     Votes:virtual ICollection<Vote>

     function bool hasVoted(string UserId){ return VotesContainsUserId.Count() == 1;}

     Id:Guid (PK)
     UserId:string (FK)
     ItemId:Guid (FK)

When i currently query the votes, i add a property to my code-first model, hasVoted, which is a not-mapped function with a parameter : UserId.

For this, all the votes has to be loaded and when the view is presented, it checks if the user has votes by looping all the fetched values.

I'd like to decrease my query load and i could do it by only loading the "hasVoted" function, without loading all the votes with the .Include("Votes") function.

Is there any way to do this or another way to decrease my query load ?

PS. for learning porpose about lambda, i'm not interested in writing a sql query.


public bool hasVoted(string userId) { 
    return this.Votes.Any(vote => vote.UserId == userId);

This query tests, whether there is a vote from the specific user, but it wouldn't help you. When you access the Votes collection, all items will be automatically loaded and the query will be performed in the memory.

If you don't want to load votes into memory, you need to use DbContext class to run the query.

public bool hasVoted(string userId, DbContext ctx) {
    return ctx.Entry<Item>(this)
        .Collection(o => o.Votes)
        .Any(vote => vote.UserID == userId);

Need Your Help

Fluent NHibernate One to Many Could Not Insert (foreign key constraint)

fluent-nhibernate nunit one-to-many

I have an error when testing my Fluent NHibernate mappings with NUnit. The problem arise when Fluent NHibernate tries to persist one object (Contact) in the database before persisting it's child (

Logic to Implement Parent Child Relationship in efficient manner

objective-c logic parent-child

I have a Table where Parent Child Relation ship is stored as: