我目前首先使用具有实体框架代码的通用存储库模式:
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;
}
模型设置如下:
modelBuilder.Entity<UserProcessed>().HasRequired(x => x.User)
.WithMany(x => x.UsersProccessed)
.Map(x => x.MapKey("UserId"));
问题是我想在上面的LINQ中添加一个子查询,所以它会做类似的事情:
SELECT u.Email
FROM Users u INNER JOIN UsersProcessed up ON u.Id = up.UserId
WHERE u.Email NOT IN
(
SELECT Email
FROM BlackList
)
但是由于User存储库是User特定的,并且模型中的User和BlackList之间没有关系设置,我不知道如何子查询BlackList。我不相信User和BlackList表之间应该存在关系,因为BlackList中的电子邮件是从第三方填充的,并且与User表无关。
答案 0 :(得分:1)
也许我误解了,但您可以在LINQ中定义一个子查询,如下所示:
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();