Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq sub query when using a repository pattern with EF code first

I currently use a generic repository pattern with Entity Framework code first:

public interface IRepository<TEntity> where TEntity : class
{
    void Add(TEntity entity);
    void Delete(TEntity entity);
    TEntity GetById(int id);
    IEnumerable<TEntity> GetAll();
}

public interface IUserRepository : IRepository<User>
{
    IEnumerable<User> GetAllWithSubQuery();
}

public interface IBlackListRepository : IRepository<BlackList>
{
}

public interface IUserProccessedRepository : IRepository<UserProcessed>
{
}

public IEnumerable<User> GetAllWithSubQuery()
{
    var result = Database.Set<User>().Where(x => x.UsersProccessed.Any())
                                     .ToList();

    return result;
}

The model is setup as follows:

modelBuilder.Entity<UserProcessed>().HasRequired(x => x.User)
                                    .WithMany(x => x.UsersProccessed)
                                    .Map(x => x.MapKey("UserId"));

The problem is that I want to add a sub query into the LINQ above so it would do something similar to this:

SELECT      u.Email
FROM        Users u INNER JOIN UsersProcessed up ON u.Id = up.UserId
WHERE       u.Email NOT IN
            (
                SELECT  Email
                FROM    BlackList
            )

But since the User repository is User specific and there is no relationship setup between the User and BlackList in the model, I don't know how to sub query BlackList. I don't believe there should be a relationship between the User and BlackList tables because emails in BlackList are populated from a third party and are independent of the User table.

like image 336
Thomas Avatar asked Jan 19 '26 00:01

Thomas


1 Answers

Perhaps I misunderstood, but you can define a sub query in LINQ like this:

IQueryable<string> blacklistedMailAddresses =
    Database.Set<Blacklist>().Select(b => b.Email);

var result = Database.Set<User>()
    .Where(x => x.UsersProccessed.Any())
    .Where(x => !blacklistedMailAddresses.Contains(x.Email))
    .ToList();
like image 141
Steven Avatar answered Jan 22 '26 03:01

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!