简体   繁体   中英

EF Core linq and conditional include and theninclude problem

I am having a problem with getting a result when trying to get objects with multiple levels. This is what I am trying to do roughly:

_context.Investors.Where(s => s.Id == userId)
    .Include(c => c.Coins) //only want this if some kind of flag is given by the user.
    .ThenInclude(ct => ct.CoinType)
    .Include(c => c.Bricks) //only want this if some kind of flag is given by the user.

Essentially I am getting a lot of flags indicating if I should include parts of the object. I got it almost to work. Like this:

_context.Investors.Where(s => s.Id == userId)
    .Select(i => new
    {
        i,
        Bricks = (details & GapiInvestorFlags.Bricks) != GapiInvestorFlags.Bricks ? null : i.Bricks,
        Offers = (details & GapiInvestorFlags.Offers) != GapiInvestorFlags.Offers ? null : i.Offers,
        Coins = (details & GapiInvestorFlags.Coins) != GapiInvestorFlags.Coins ? null : i.Coins,
        CoinTransactions = (details & GapiInvestorFlags.CoinTransactions) != GapiInvestorFlags.CoinTransactions ? null : i.CoinTransactions,
        OfferTransactions = (details & GapiInvestorFlags.OfferTransactions) != GapiInvestorFlags.OfferTransactions ? null : i.OfferTransactions,
        BuyTransactions = (details & GapiInvestorFlags.BuyTransactions) != GapiInvestorFlags.BuyTransactions ? null : i.BuyTransactions,
        SellTransactions = (details & GapiInvestorFlags.SellTransactions) != GapiInvestorFlags.SellTransactions ? null : i.SellTransactions
    }).AsEnumerable()
    .Select(e => e.i).FirstOrDefault();

This works except that the Coins section also has a cointype in it so I need to include it too. But when I add my code, the whole section stops working.

This is what I tried:

_context.Investors.Where(s => s.Id == userId)
    .Include(c => c.Coins)
    .ThenInclude(ct => ct.CoinType)
    .Select(i => new
    {
        i,
        Bricks = (details & GapiInvestorFlags.Bricks) != GapiInvestorFlags.Bricks ? null : i.Bricks,
        Offers = (details & GapiInvestorFlags.Offers) != GapiInvestorFlags.Offers ? null : i.Offers,
        Coins = (details & GapiInvestorFlags.Coins) != GapiInvestorFlags.Coins ? null : i.Coins.Select(c => new { c, c.CoinType }).ToList(),
        CoinTransactions = (details & GapiInvestorFlags.CoinTransactions) != GapiInvestorFlags.CoinTransactions ? null : i.CoinTransactions,
        OfferTransactions = (details & GapiInvestorFlags.OfferTransactions) != GapiInvestorFlags.OfferTransactions ? null : i.OfferTransactions,
        BuyTransactions = (details & GapiInvestorFlags.BuyTransactions) != GapiInvestorFlags.BuyTransactions ? null : i.BuyTransactions,
        SellTransactions = (details & GapiInvestorFlags.SellTransactions) != GapiInvestorFlags.SellTransactions ? null : i.SellTransactions
    }).AsEnumerable()
    .Select(e => e.i).FirstOrDefault();

I really can't tell why it does not work.

Basically when I change:

i.Coins

To

i.Coins.Select(c => new { c, c.CoinType }).ToList()

it stops working.

The technique you are using is not really explicit loading ( Include / ThenInclude ), but trick based on projection and EF Core navigation property fix-up, so I can't say why it stops working. EF Core still processes projections and includes differently, so it might be a defect in the current processing.

Implementing conditional include at the root query level is relatively easy. Note that the Include method starts from (is defined for) IQueryable<TEntity> and the returned IIncludableQueryable<TEntity, TPreviousProperty>> is also IQueryable<TEntity> . Which means you can keep IQueryable<T> query variable and apply conditional transformations similar to chained Where operators.

To make that easier, you could create a custom helper extension method like this:

public static IQueryable<T> If<T>(
    this IQueryable<T> source,
    bool condition,
    Func<IQueryable<T>, IQueryable<T>> transform
)
{ 
    return condition? transform(source) : source;
}

and use it like this:

_context.Investors.Where(s => s.Id == userId)
    .If(flagCoins, q => q.Include(e => e.Coins)
        .ThenInclude(e => e.CoinType))
    .If(flagBricks, q => q.Include(e => e.Bricks))

If you need something similar for the nested levels ( ThenInclude ), then add the following 2 extension methods:

public static IQueryable<T> If<T, P>(
    this IIncludableQueryable<T, P> source,
    bool condition,
    Func<IIncludableQueryable<T, P>, IQueryable<T>> transform
)
    where T : class
{
    return condition ? transform(source) : source;
}

public static IQueryable<T> If<T, P>(
    this IIncludableQueryable<T, IEnumerable<P>> source,
    bool condition,
    Func<IIncludableQueryable<T, IEnumerable<P>>, IQueryable<T>> transform
)
    where T : class
{
    return condition ? transform(source) : source;
}

which will allow you to use something like this:

_context.Investors.Where(s => s.Id == userId)
    .If(flagCoins, q => q.Include(e => e.Coins)
        .If(flagCoinType, q2 => q2.ThenInclude(e => e.CoinType)))
    .If(flagBricks, q => q.Include(e => e.Bricks))

you can use my extension method.

  1. Using:
 var filteredTransactions = _transactionRepository.GetAll()
                    .Where(x => x.CreationTime.Ticks <= input.FetchingTikes)
                    .IncludeIf(input.Filter.IsNotNullOrWhitespace(), t => t.DestinationAccountFk.Merchant, t => t.SourceAccountFk.UserFk)
  1. Extenstion:
 public static IQueryable<TEntity> IncludeIf<TEntity>([NotNull] this 
   IQueryable<TEntity> source
                ,bool condition
                ,params Expression<Func<TEntity, object>>[] 
    navigationPropertyPaths)
                where TEntity : class
            {
                if (condition)
                {
                    if (navigationPropertyPaths.IsNotNullOrEmpty())
                    {
                        foreach (var navigationPropertyPath in 
   navigationPropertyPaths)
                        {
                            source = source.Include(navigationPropertyPath);
                        }
                    }
                }
                return source;
            }
  1. Other extensions:
        public static bool IsNotNullOrEmpty<T>(this IEnumerable<T> list)
        {
            if (list.IsNotNull() && list.IsNotEmpty())
            {
                return true;
            }
            return false;
        }

        public static bool IsNotNull(this object obj)
        {
            if (obj != null)
            {
                return true;
            }
            return false;
        }

        public static bool IsNotEmpty<T>(this IEnumerable<T> list)
        {
            if (list.Count() > 0)
            {
                return true;
            }
            return false;
        }



       

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM