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.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.