Anonymous type transfer as T

In the Entity Framework, you can run and bind custom queries on the fly, for example ...

protected class NitrogenMoisutreContainer
{
    public double MinN { get; set; }
    public double MaxN { get; set; }
    public double MinM { get; set; }
    public double MaxM { get; set; }
}

// ...

var q = dbcontext.Database.SqlQuery<NitrogenMoisutreContainer>(@"SELECT MAX(NitrogenBalance) as MaxN, MIN(NitrogenBalance) as MinN, MAX(FCWaterPercent) as MaxM, MIN(FCWaterPercent) as MinM
                                                                    FROM agZoneProjectionGrowthStages
                                                                    WHERE NitrogenBalance > 0 AND FCWaterPercent > 0").First();

The problem is that it seems dirty to me. I had to create this class for one request, and I will never use it for anything else . The results are used exactly on one line where it is executed.

Is there a way to return an anonymous type? Even if I had to declare it first, like this ...

var anonItem = new {
    MinN = 0d,
    MaxN = 0d,
    MinM = 0d,
    MaxM = 0d
};

var q = dbcontext.Database.SqlQuery<anonItem.GetType()>("...");

I just can't figure out how to pass my anonymous type Typeas T. Is it possible?

+5
source share
2 answers

The problem is that it seems dirty to me. I had to create this class for one request, and I will never use it for anything else . The results are used exactly on one line where it is executed.

I do not see this as a problem.

Is there a way to return an anonymous type?

tuple.

+2

, , . .

public static IEnumerable<T> GetObjects<T>(T exampleItem, string sqlQuery) { ... }
var q = GetObjects(anonItem, @"");

, , , , named .

+5

All Articles