In the Entity Framework you can run and bind custom queries on-the-fly like so...
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, to me, this feels messy. I had to create this class for one query and I will never use it again for anything else. The results are used exactly one line down from where it is executed.
Is there a way I can 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 in my anonymous type's Type
as T
. Is it possible?
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.
From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
This can be done if you set it up so the type can be inferred. E.g.
public static IEnumerable<T> GetObjects<T>(T exampleItem, string sqlQuery) { ... }
var q = GetObjects(anonItem, @"");
I think this is a bit hackish, and I'd suggest trying another approach, like actually making the named class or using a tuple.
The problem is that, to me, this feels messy. I had to create this class for one query and I will never use it again for anything else. The results are used exactly one line down from where it is executed.
I don't see this as a problem.
Is there a way I can return an anonymous type?
You could create a tuple instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With