ImmortalStrawberry
ImmortalStrawberry

Reputation: 6091

How to return a new object of a concrete type using LINQ/Linq2E?

I have the following select statement which appears syntactically correct:

 var accounts = from i in db.IRSBASEFLs
                           join vr in db.VSARules on i.VSACode equals vr.VSACode into rules
                           from rule in rules.DefaultIfEmpty()
                           select new ImporterAccount(i, rule, RuleType.Liquidity);

However, this throws:

Only parameterless constructors and initializers are supported in LINQ to Entities.

I've tried adding a "builder" class to return a new ImporterAccount, but this too fails, this time with:

LINQ to Entities does not recognize the method 'IrsalDAL.ImporterAccount CreateImporterAccount(IrsalDAL.IRSBASEFL, IrsalDAL.VSARule, IrsalUtilities.RuleType)' method, and this method cannot be translated into a store expression.

I need to perform a calculation, ideally in the constructor, so I am a little confused as to how to acheive this?

Why is this throwing a L2E exception when the class is not part of my entity model?

How can I return a new object and perform a calculation on it?

Upvotes: 1

Views: 747

Answers (1)

Amith George
Amith George

Reputation: 5916

Am not sure what the solution to your problem is, but you can work around it as such:

var tempAccounts = from i in db.IRSBASEFLs
                   join vr in db.VSARules on i.VSACode equals vr.VSACode into rules
                   from rule in rules.DefaultIfEmpty()
                   select new { VarI = i, Rule = rule, Liquidity = RuleType.Liquidity};

var accounts = tempAccounts.Select(x => new ImporterAccount(x.VarI, x.rule, x.Liquidity));

Hope it helps :)

Edit 1: Regarding the "close existing data reader error", A google search returns many results, with the first one being a SO question. The accepted answer is:

It is not about closing connection. EF manages connection correctly. My understanding of this problem is that there are multiple data retrieval commands executed on single connection (or single command with multiple selects) while next DataReader is executed before first one has completed the reading. The only way to avoid the exception is to allow multiple nested DataReaders = turn on MultipleActiveResultSets. Another scenario when this always happens is when you iterate through result of the query (IQueryable) and you will trigger lazy loading for loaded entity inside the iteration.

Upvotes: 1

Related Questions