Jordec
Jordec

Reputation: 1562

Can't add calculated value to IQueryable

I'm running an EF statement where I need to calculate de deductibles. After long trying, I can't seem to add a custom function in a .Select() statement. Instead I'm trying to add the values after my .Select() statement.

The problem here is, in my CalculateDeductibles() I can't seem to add any values to item.Deductibles.

The GetDeductibles(item.RequestId) is a rather heavy funtion that does several extra queries, so I'm trying to prevent to convert my IQueryable to an IList object.

So there are actually 2 questions:

  1. Can I have the GetDeductibles() function directly in my .Select() statement?
  2. Can I somehow (with keeping an eye on performance) add the value after I did my .Select()

Code:

public IQueryable<ReinsuranceSlip> GetReinsuranceSlipsOverview(int userId, int companyId, string owner, string ownerCompany)
{
    IQueryable<ReinsuranceSlip> model = null;

    model = _context.Request
        .Where(w => w.RequestGroup.ProgramData.MCContactId == userId)
        .Select(x => new ReinsuranceSlip()
        {
            Id = x.Id,
            RequestId = x.Id,
            LocalPolicyNumber = x.LocalPolicyNumber,
            BusinessLine = x.RequestGroup.ProgramData.BusinessLine.DisplayName,
            BusinessLineId = x.RequestGroup.ProgramData.BusinessLine.Id,
            ParentBroker = x.RequestGroup.ProgramData.Broker.Name,
            LocalBroker = x.Broker.Name,
            InceptionDate = x.InceptionDate,
            RenewDate = x.RenewDate,
            //Deductibles = CalculateDeductibles(x)
        });

    CalculateDeductibles(model);

    return model;
}


private void CalculateDeductibles(IQueryable<ReinsuranceSlip> model)
{
    //model.ForEach(m => m.Deductibles = GetDeductibles(m.RequestId));
    foreach (var item in model)
    {
        item.Deductibles = GetDeductibles(item.RequestId);
    }
}

Upvotes: 0

Views: 1025

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30512

You'll have to understand the differences between an IEnumerable and an IQueryable.

An IEnumerable object holds everything to enumerate over the elements in the sequence that this object represents. You can ask for the first element, and once you've got it, you can repeatedly ask for the next element until there is no more next element.

An IQueryable works differently. An IQueryable holds an Expression and a Provider. The Expression is a generic description of what data should be selected. The Provider knows who has to execute the query (usually a database), and it knows how to translate the Expression into a format that the Provider understands.

There are two types of LINQ functions: the ones that return IQueryable<TResult> and the ones that return TResult. Functions form the first type do not execute the query, they will only change the expression. They use deferred execution. Functions of the second group will execute the query.

When the query must be executed, the Provider takes the Expression and tries to translate it into the format that the process that executes the query understand. If this process is a relational database management system this will usually be SQL.

This translation is the reason that you can't add your own functionality: the Expression must be translatable to SQL, and the only thing that your functions may do is call functions that will change the Expression to something that can be translated into SQL.

In fact, even entity framework does not support all LINQ functionalities. There is a list of Supported and Unsupported LINQ methods

Back to your questions

Can I have GetDeductibles directly in my query?

No you can't, unless you can make it thus simple that it will only change the Expression using only supporte LINQ methods. You'll have to write this in the format of an extension function. See extension methods demystified

Your GetDeductibles should have an IQueryable<TSource> as input, and return an IQueryable<TResult> as output:

static class QueryableExtensions
{
    public static IQueryable<TResult> ToDeductibles<TSource, TResult, ...>(
       this IQueryable<TSource> source,
       ... other input parameters, keySelectors, resultSelectors, etc)
    {
         IQueryable<TResult> result = source... // use only supported LINQ methods
         return result;
    } 
}

If you really need to call other local functions, consider calling AsEnumerable just before calling the local functions. The advantage above ToList is that smart IQueryable providers, like the one in Entity Framework will not fetch all items but the items per page. So if you only need a few ones, you won't have transported all data to your local process. Make sure you throw away all data you don't need anymore before calling AsEnumerable, thus limiting the amount of transported data.

Can I somehow add the value after I did my .Select()

LINQ is meant to query data, not to change it. Before you can change the data you'll have to materialize it before changing it. In case of a database query, this means that you have a copy of the archived data, not the original. So if you make changes, you'll change the copies, not the originals.

When using entity framework, you'll have to fetch every item that you want to update / remove. Make sure you do not select values, but select the original items.

NOT:

var schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
   .Select(school = new
   {
       ... // you get a copy of the values: fast, but not suitable for updates
   })
   .FirstOrDefault();

BUT:

School schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
   .FirstOrDefault()

Now your DbContext has the original School in its ChangeTracker. If you change the SchoolToUpdate, and call SaveChanges, your SchoolToUpdate is compared with the original School, to check if the School must be updated.

If you want, you can bypass this mechanism, by Attaching a new School directly to the ChangeTracker, or call a Stored procedure.

Upvotes: 0

mafirat
mafirat

Reputation: 287

Updated and Sorry for the first version of this answer. I didn't quite understand.
Answer 1: IQueryable is using to creating a complete SQL statement to call in SQL Server. So If you want to use IQueryable, your methods need to generate statements and return it. Your GetDetuctibles method get request Id argument but your queryable model object didn't collect any data from DB yet, and it didn't know x.Id value. Even more, your GetCarearDetuctiples get an argument so and with that argument generates a queryable object and after some calculations, it returns decimal. I mean yes you can use your methods in select statement but it's really complicated. You can use AsExpendable() LINQ method and re-write your methods return type Expression or Iqueryable.
For detailed info you should check. This:

Entity Navigation Property IQueryable cannot be translated into a store expression
and this: http://www.albahari.com/nutshell/predicatebuilder.aspx

And you also should check this article to understand IQueryable interface: https://samueleresca.net/2015/03/the-difference-between-iqueryable-and-ienumerable/

Answer 2: You can use the IEnumerable interface instead IQueryable interface to achieve this. It will be easy to use in this case. You can make performance tests and improve your methods by time.

But if I were you, I'd consider using Stored Procedures for performance gain.

Upvotes: 1

Related Questions