tfa
tfa

Reputation: 1699

C# Linq Conditional Cast object to EF table Type

Currently have

var orders = (from x in _contextComet.vwOrderSummary)
if (StartDate != null) 
{
    orders = orders.Where(x => x.DateCreated >= StartDate);
}

Now I need to change it to the following and then use the queryable object for further filtering within the same function.

if (inTestMode)
{
    var orders = (from x in _contextComet.vwOrderSummaryTest)
}
else
{
    var orders = (from x in _contextComet.vwOrderSummary)
}
if (StartDate != null) 
{
    orders = orders.Where(x => x.DateCreated >= StartDate);
}

Upvotes: 0

Views: 478

Answers (2)

tfa
tfa

Reputation: 1699

Got it thanks to Gilad added .ProjectTo();

IQueryable<OrderSummary> orders = inTestMode ?
_contextComet.vwOrderSummaryAlls.Select(item => new OrderSummary { ID = item.ID }) :
_contextComet.vwOrderSummaries.ProjectTo<OrderSummary>();

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37281

IQueryable<OrderSummary> orders = inTestMode ?
    _contextComet.vwOrderSummaryTest.Select(item => 
        new OrderSummary { /*Populate properties*/ }) :
    _contextComet.vwOrderSummary; //Assuming item type of table is OrderSummary

if (StartDate != null) 
{
    orders = orders.Where(x => x.DateCreated >= StartDate);
}

Better Approach: By the names of your tables (vwOrderSummary, vwOrderSummaryTest) I'd say you are mixing dev and prod environment. Do not check for the debug mode vs prod mode and by that select from different tables but have 2 separate databases and depending on mode plug a different connection string. This can be done with MSBuild nicely.

Upvotes: 1

Related Questions