I want to include related entities with some filter condition. Is this possible ?? I don't want to write projection query for this. So I was trying to achieve this by below code...... but it's not working.
My Domain Object
public class UserRef : BaseModel
{
public static readonly System.Linq.Expressions.Expression<Func<UserRef, ICollection<UserNewsLetterMap>>> UserNewsLetterExp =
UserNewsLetterExp => UserNewsLetterExp.UserNewsLetterMaps;
public UserRef()
{
UserNewsLetterMaps = new HashSet<UserNewsLetterMap>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<UserNewsLetterMap> UserNewsLetterMaps { get; set; }
}
My Repository code
var user = this._context.UserRefs.AsExpandable()
.Include(u => UserRef.UserNewsLetterExp.Invoke(u).Where(news => news.Subscribe).Select(news => news.DocTypeRef))
.SingleOrDefault(u => u.UserName == userName);
What is the best practics or best solution for this?
Thanks in advance :)
As of now I found 2 solution for my problem 1. Projection query
var result = db.UserRef
.Select(p => new
{
User= p,
UserNewsLetterMaps = p.UserNewsLetterMaps.Where(c => c.Subscribe == true)
})
.ToList();
Load related entity using eager loading.
_context.Entry(user).Collection(u => u.UserNewsLetterMaps) .Query().Where(news => news.Subscribe) .Select(news => news).Include(news => news.DocTypeRef) .Load();