How to create an anonymous object with property names determined dynamically? - c#

Given an array of values, I would like to create an anonymous object with properties based on these values. The property names would be simply "pN" where N is the index of the value in the array.
For example, given
object[] values = { 123, "foo" };
I would like to create the anonymous object
new { p0 = 123, p1 = "foo" };
The only way I can think of to do this would be to to use a switch or if chain up to a reasonable number of parameters to support, but I was wondering if there was a more elegant way to do this:
object[] parameterValues = new object[] { 123, "foo" };
dynamic values = null;
switch (parameterValues.Length)
{
case 1:
values = new { p0 = parameterValues[0] };
break;
case 2:
values = new { p0 = parameterValues[0], p1 = parameterValues[1] };
break;
// etc. up to a reasonable # of parameters
}
Background
I have an existing set of methods that execute sql statements against a database. The methods typically take a string for the sql statement and a params object[] for the parameters, if any. The understanding is that if the query uses parameters, they will be named #p0, #p1, #p2, etc..
Example:
public int ExecuteNonQuery(string commandText, CommandType commandType, params object[] parameterValues) { .... }
which would be called like this:
db.ExecuteNonQuery("insert into MyTable(Col1, Col2) values (#p0, #p1)", CommandType.Text, 123, "foo");
Now I would like to use Dapper within this class to wrap and expose Dapper's Query<T> method, and do so in a way that would be consistent with the existing methods, e.g. something like:
public IEnumerable<T> ExecuteQuery<T>(string commandText, CommandType commandType, params object[] parameterValues) { .... }
but Dapper's Query<T> method takes the parameter values in an anonymous object:
var dog = connection.Query<Dog>("select Age = #Age, Id = #Id", new { Age = (int?)null, Id = guid });
leading to my question about creating the anonymous object to pass parameters to Dapper.
Adding code using the DynamicParameter class as requested by #Paolo Tedesco.
string sql = "select * from Account where Id = #p0 and username = #p1";
dynamic values = new DynamicParameter(123, "test");
var accounts = SqlMapper.Query<Account>(connection, sql, values);
throws an exception at line 581 of Dapper's SqlMapper.cs file:
using (var reader = cmd.ExecuteReader())
and the exception is a SqlException:
Must declare the scalar variable "#p0".
and checking the cmd.Parameters property show no parameters configured for the command.

You are misusing Dapper, you should never need to do this, instead either implement IDynamicParameters or use the specific extremely flexible DynamicParameters class.
In particular:
string sql = "select * from Account where Id = #id and username = #name";
var values = new DynamicParameters();
values.Add("id", 1);
values.Add("name", "bob");
var accounts = SqlMapper.Query<Account>(connection, sql, values);
DynamicParameters can take in an anonymous class in the constructor. You can concat DynamicParameters using the AddDynamicParams method.
Further more, there is no strict dependency on anon-types. Dapper will allow for concrete types as params eg:
class Stuff
{
public int Thing { get; set; }
}
...
cnn.Execute("select #Thing", new Stuff{Thing = 1});
Kevin had a similar question: Looking for a fast and easy way to coalesce all properties on a POCO - DynamicParameters works perfectly here as well without any need for magic hoop jumping.

Not exactly an anonymous object, but what about implementing a DynamicObject which returns values for p1 ... pn based on the values in the array? Would that work with Dapper?
Example:
using System;
using System.Dynamic;
using System.Text.RegularExpressions;
class DynamicParameter : DynamicObject {
object[] _p;
public DynamicParameter(params object[] p) {
_p = p;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
Match m = Regex.Match(binder.Name, #"^p(\d+)$");
if (m.Success) {
int index = int.Parse(m.Groups[1].Value);
if (index < _p.Length) {
result = _p[index];
return true;
}
}
return base.TryGetMember(binder, out result);
}
}
class Program {
static void Main(string[] args) {
dynamic d1 = new DynamicParameter(123, "test");
Console.WriteLine(d1.p0);
Console.WriteLine(d1.p1);
}
}

You cannot dynamically create anonymous objects. But Dapper should work with dynamic object. For creating the dynamic objects in a nice way, you could use Clay. It enables you to write code like
var person = New.Person();
person["FirstName"] = "Louis";
// person.FirstName now returns "Louis"

Related

How to cast an object to any type using object.GetType()

I have an object type variable where I want to cast it to its original data type. Data type could be anything (int, enum, class, etc)
(object.GetType())object is not working
Edited:
The reason I want to cast it again to original, because I'm building a cosmos db query with multiple parameters
I have a method QueryCosmos(Dictionary<string, object> parameters) where key is the field name in cosmos, and value is the value of the field that matches the condition (it could be any data type).
static string QueryCosmos(Dictionary<string, object> parameters)
{
var sb = new StringBuilder($"SELECT * FROM c WHERE ");
foreach (var p in parameters)
{
if (!(p.Value is string))
{
// this handles non-string data types
var value = p.Value == null ? "null" : p.Value.ToString().ToLower();
sb.Append($"c.{p.Key} = {value} and ");
}
else
{
sb.Append($"c.{p.Key} = '{p.Value}' and ");
}
}
return sb.ToString().Substring(0, sb.ToString().LastIndexOf(" and "));
}
My issue is with this line of code var value = p.Value == null ? "null" : p.Value.ToString().ToLower();
If I pass on an enum type, doesn't match the data in cosmos. Because in cosmos, this is stored as the numeric value of the enum. I would need it to convert to its numeric value. There are multiple possible enum types that can be passed. That's the reason why I wanted a dynamic way to covert to original data type
Hope this clears up the concern
As you're targeting Azure CosmosDB, you don't need to write your own query-generator, the CosmosDB client library (Microsoft.Azure.Cosmos) has one built-in.
In your case, use QueryDefinition and WithParameter to build a strongly-typed query. The WithParameter method accepts values as object and it handles type-specific logic for you.
As you are using a dynamic-query my code below shows how you can safely build a query's WHERE clause from a dictionary by using named-parameters.
Never embed query parameter values directly in the query SQL itself because doing so opens yourself up to SQL injection which is a very bad thing.
Update for enum:
I'll admit that I'm unfamiliar with the Azure CosmosDB client library, though I did take a quick look at the documentation and poked around the library in ILSpy.
As for handling enum values: the QueryDefinition.WithParameter method should handle enum values correctly as it preserves the boxed enum values in its .Value property.
If it doesn't, then converting any enum to an Int32 can be done like so - albeit with boxing (while it is possible to cast any enum to Int64 without casting that requires runtime IL emit which is beyond the scope of this answer, but I have an implementation in my GitHub Gists if you're interested):
I've updated the code below to use this foreach loop which checks for Enum (which matches any and all enum types, regardless of their underlying-type, though this example will fail if you have any enum : Int64 enums with values outside Int32's range - but that's trivial to fix and so is left as an exercise for the reader).
foreach( var kvp in parameters )
{
if( kvp.Value is Enum e )
{
Int32 enumAsInt32 = (Int32)Convert.ChangeType( e, TypeCode.Int32 );
query = query.WithParameter( kvp.Key, enumAsInt32 );
}
else
{
query = query.WithParameter( kvp.Key, kvp.Value );
}
}
The rest of my original answer:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
//
public static QueryDefinition BuildCosmosQuery( Dictionary<String,Object> parameters )
{
String sqlText = "SELECT * FROM foobar AS f WHERE " + GetWhereClauses( "f", parameters.Keys );
QueryDefinition query = new QueryDefinition( sqlText );
foreach( var kvp in parameters )
{
if( kvp.Value is Enum e )
{
Int32 enumAsInt32 = (Int32)Convert.ChangeType( e, TypeCode.Int32 );
query = query.WithParameter( kvp.Key, enumAsInt32 );
}
else
{
query = query.WithParameter( kvp.Key, kvp.Value );
}
}
return query;
}
private static String GetWhereClauses( String tableAlias, IEnumerable<String> parameterNames )
{
return parameterNames
.Select( pn => "{0}.{1} = #{1}".FmtInv( tableAlias, pn ) )
.StringJoin( separator: " AND " );
}
//
public static class Extensions
{
public static String StringJoin( this IEnumerable<String> source, String separator )
{
return String.Join( values: source, separator: separator );
}
public static String FmtInv( this String format, params Object[] args )
{
return String.Format( CultureInfo.InvariantCulture, format, args: args );
}
}
See the QueryWithSqlParameters method in this code sample to see how to use QueryDefinition.
I've not looked at your new edit, but hopefully my answer is still relevant.
If you wish to cast an instance to its known concrete class type then you could use the as operator.
Here's some example code:
using System.IO;
using System;
using System.Collections.Generic;
class Program
{
public class BaseClass{
public string Base="BaseClass";
}
public class Class1:BaseClass{
public string Value="Class 1";
}
public class Class2:BaseClass{
public string Value="Class 2";
public string AnotherValue="Another value";
}
static void Main()
{
List<BaseClass> list=new List<BaseClass>(){new Class1(), new Class2()};
foreach( var item in list)
{
Console.WriteLine($"Item.Base = {item.Base}");
if(typeof(Class1).IsAssignableFrom( item.GetType() ))
{
Console.WriteLine($"Item.Value = {(item as Class1).Value}");
}
if(typeof(Class2).IsAssignableFrom( item.GetType() ))
{
Console.WriteLine($"Item.Value = {(item as Class2).Value}");
Console.WriteLine($"Item.Value = {(item as Class2).AnotherValue}");
}
}
}
}
This will give you the output of:
Item.Base = BaseClass
Item.Value = Class 1
Item.Base = BaseClass
Item.Value = Class 2
Item.Value = Another value

How do I pass JSON as a primitive PostgreSQL type to a function using Dapper?

I have a PostgreSQL function that takes in a parameter of type json. Using Dapper, how do I execute a call that passes the object to the PostgreSQL function such that PostgreSQL recognizes the type as json instead of as text?
Example PostgreSQL Function that takes in json type
CREATE OR REPLACE FUNCTION testfuncthattakesinjson(heroes json)
RETURNS SETOF characters
LANGUAGE 'sql'
STABLE
ROWS 100
AS $BODY$
SELECT c.*
FROM characters c
JOIN json_array_elements(heroes) j
ON c.first_name = j->>'first_name'
AND c.last_name = j->>'last_name';
$BODY$;
Broken Example C# Integration Test
[Test]
public void Query_CallFunctionThatTakesInJsonParameter_FunctionUsesJsonType()
{
using (var conn = new NpgsqlConnection(Db.GetConnectionStringToDatabase()))
{
var funcName = "testfuncthattakesinjson";
var expect = CharacterTestData.Where(character => character.id <= 3);
var jsonObj = JArray.FromObject(CharacterTestData
.Where(character => character.id <= 3)
.Select(character => new Hero(character))
.ToList());
SqlMapper.AddTypeHandler(new JArrayTypeHandler());
// Act
var results = conn.Query<Character>(funcName, new
{
heroes = jsonObj
}, commandType: CommandType.StoredProcedure);
// Assert
CollectionAssert.AreEquivalent(expect, results);
}
}
Supporting JArrayTypeHandler
internal class JArrayTypeHandler : SqlMapper.TypeHandler<JArray>
{
public override JArray Parse(object value)
{
throw new NotImplementedException();
}
public override void SetValue(IDbDataParameter parameter, JArray value)
{
parameter.Value = value;
}
}
In this current iteration, I've added a SqlMapper.TypeHandler. (At the moment, I'm only concerned with passing the JArray to PostgreSQL, hence the NotImplmentedException for Parse.)
With this example, I get the following exception:
System.NotSupportedException: 'The CLR array type Newtonsoft.Json.Linq.JArray isn't supported by Npgsql or your PostgreSQL. If you wish to map it to an PostgreSQL composite type array you need to register it before usage, please refer to the documentation.'
In past iterations, I've also tried things like using a List<Hero> type handler and letting that type handler deal with the Json conversion.
I've also tried adding the Npgsql.Json.NET Nuget package extension for Npgsql and call conn.TypeMapper.UseJsonNet() in my test method, but that didn't seem to have any effect.
And if I do anything to serialize the object to a JSON string, then I get a different error (below), which makes sense.
Npgsql.PostgresException: '42883: function testfuncthattakesinjson(heroes => text) does not exist'
So, it is possible to use Dapper to pass a JSON object as a PostgreSQL primitive to a function?
You can use Dapper's ICustomQueryParameter interface.
public class JsonParameter : ICustomQueryParameter
{
private readonly string _value;
public JsonParameter(string value)
{
_value = value;
}
public void AddParameter(IDbCommand command, string name)
{
var parameter = new NpgsqlParameter(name, NpgsqlDbType.Json);
parameter.Value = _value;
command.Parameters.Add(parameter);
}
}
Then your Dapper call becomes:
var results = conn.Query<Character>(funcName, new
{
heroes = new JsonParameter(jsonObj.ToString())
}, commandType: CommandType.StoredProcedure);

How to prevent returned Json being split?

I'm using Dapper to read data from SQL Server. I have a SQL statement that returns a long Json result but the issue is this result being split into 3 rows with 2033 characters max per row, then Dapper can't parse the returned result because it's invalid Json.
How to prevent this splitting or how to make Dapper deal with it?
This is my code:
SqlMapper.ResetTypeHandlers();
SqlMapper.AddTypeHandler(new JsonTypeHandler<List<Product>>());
const string sql = #"SELECT
*,
(SELECT * FROM Balance b
WHERE p.SKU = b.SKU
FOR JSON PATH) AS [Balances]
FROM Product p
WHERE SKU IN #SKUs
FOR JSON PATH";
var connection = new SqlConnection("myconnection");
return connection.QuerySingleAsync<List<Product>>(sql, new{SKUs = new[] {"foo", "bar"}} });
And the code of TypeHandler:
public class JsonTypeHandler<T> : SqlMapper.TypeHandler<T>
{
public override T Parse(object value)
{
return JsonConvert.DeserializeObject<T>(value.ToString());
}
public override void SetValue(IDbDataParameter parameter, T value)
{
parameter.Value = JsonConvert.SerializeObject(value);
}
}
And here is how I run this SQL in DataGrip
Edit:
Here is the error message:
Newtonsoft.Json.JsonSerializationException : Unexpected end when deserializing object. Path '[0].Balances[4].WarehouseId', line 1, position 2033.
My solution is writing another extension method that wraps Query<string> method likes below:
public static T QueryJson<T>(this IDbConnection cnn, string sql, object param = null,
IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null,
CommandType? commandType = null) where T: class
{
var result = cnn.Query<string>(sql, param, transaction, buffered, commandTimeout, commandType).ToList();
if (!result.Any())
return default(T);
// Concats
var sb = new StringBuilder();
foreach (var jsonPart in result)
sb.Append(jsonPart);
var settings = new JsonSerializerSettings
{
// https://github.com/danielwertheim/jsonnet-contractresolvers
// I use this Contract Resolver to set data to private setter properties
ContractResolver = new PrivateSetterContractResolver()
};
// Using Json.Net to de-serialize objects
return JsonConvert.DeserializeObject<T>(sb.ToString(), settings);
}
This solution works quite well and slower then multiple mapping method when query large data (1000 objects took 2.7 seconds in compare to 1.3 seconds).

Dynamic Linq query on relationship with foreign key of type Guid

I'm using System.Linq.Dynamic to query an IQueryable datasource dynamically using a where-clause in a string format, like this:
var result = source.Entities.Where("City = #0", new object[] { "London" });
The example above works fine. But now I want to query on a foreign key-property of type Guid like this:
var result = source.Entities.Where("CompanyId = #0", new object[] { "838AD581-CEAB-4B44-850F-D05AB3D791AB" });
This won't work because a Guid can't be compared to a string by default. And I have to provide the guid as a string because it's originally coming from a json-request and json does not support guid's.
Firstly, is this even a correct way of querying over a relationship or is there an other syntax for doing this?
Secondly, how do I modify Dynamic.cs from the Dynamic Linq-project to automatically convert a string to guid if the entity-property being compared with is of type guid?
You have many ways for solving. Simplest, as i think, will be change your query like this
var result = source.Entities.Where("CompanyId.Equals(#0)", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });
If you want use operators = and == then in Dynamic.cs you need change interface IEqualitySignatures : IRelationalSignatures like this
interface IEqualitySignatures : IRelationalSignatures
{
....
F(Guid x, Guid y);
....
}
after that you can use next query
var result = source.Entities.Where("CompanyId=#0", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });
OR
var result = source.Entities.Where("CompanyId==#0", new object[] { Guid.Parse("838AD581-CEAB-4B44-850F-D05AB3D791AB") });
But if you want use string parameter you need change ParseComparison method in ExpressionParser class. You need add yet another checking for operand types like this
....
//you need add this condition
else if(left.Type==typeof(Guid) && right.Type==typeof(string)){
right = Expression.Call(typeof(Guid).GetMethod("Parse"), right);
}
//end condition
else {
CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures), op.text, ref left, ref right, op.pos);
}
....
and then you query will be work
var result = source.Entities.Where("CompanyId = #0", new object[] { "838AD581-CEAB-4B44-850F-D05AB3D791AB" });

How do I create and access a new instance of an Anonymous Class passed as a parameter in C#?

I have created a function that takes a SQL command and produces output that can then be used to fill a List of class instances. The code works great. I've included a slightly simplified version without exception handling here just for reference - skip this code if you want to jump right the problem. If you have suggestions here, though, I'm all ears.
public List<T> ReturnList<T>() where T : new()
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
Type objectType = typeof (T);
FieldInfo[] typeFields = objectType.GetFields();
while (nwReader.Read())
{
T obj = new T();
foreach (FieldInfo info in typeFields)
{
for (int i = 0; i < nwReader.FieldCount; i++)
{
if (info.Name == nwReader.GetName(i))
{
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
nwReader.Close();
return fdList;
}
As I say, this works just fine. However, I'd like to be able to call a similar function with an anonymous class for obvious reasons.
Question #1: it appears that I must construct an anonymous class instance in my call to my anonymous version of this function - is this right? An example call is:
.ReturnList(new { ClientID = 1, FirstName = "", LastName = "", Birthdate = DateTime.Today });
Question #2: the anonymous version of my ReturnList function is below. Can anyone tell me why the call to info.SetValue simply does nothing? It doesn't return an error or anything but neither does it change the value of the target field.
public List<T> ReturnList<T>(T sample)
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
// Cannot use FieldInfo[] on the type - it finds no fields.
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read())
{
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyDescriptor info in properties)
{
for (int i = 0; i < nwReader.FieldCount; i++)
{
if (info.Name == nwReader.GetName(i))
{
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
nwReader.Close();
return fdList;
}
Any ideas?
Note: when I tried to use the FieldInfo array as I did in the function above, the typeFields array had zero elements (even though the objectType shows the field names - strange). Thus, I use TypeDescriptor.GetProperties instead.
Any other tips and guidance on the use of reflection or anonymous classes are appropriate here - I'm relatively new to this specific nook of the C# language.
UPDATE: I have to thank Jason for the key to solving this. Below is the revised code that will create a list of anonymous class instances, filling the fields of each instance from a query.
public List<T> ReturnList<T>(T sample)
{
List<T> fdList = new List<T>();
myCommand.CommandText = QueryString;
SqlDataReader nwReader = myCommand.ExecuteReader();
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read())
{
int objIdx = 0;
object[] objArray = new object[properties.Count];
foreach (PropertyDescriptor info in properties)
objArray[objIdx++] = nwReader[info.Name];
fdList.Add((T)Activator.CreateInstance(sample.GetType(), objArray));
}
nwReader.Close();
return fdList;
}
Note that the query has been constructed and the parameters initialized in previous calls to this object's methods. The original code had an inner/outer loop combination so that the user could have fields in their anonymous class that didn't match a field. However, in order to simplify the design, I've decided not to permit this and have instead adopted the db field access recommended by Jason. Also, thanks to Dave Markle as well for helping me understand more about the tradeoffs in using Activator.CreateObject() versus GenUninitializedObject.
Anonymous types encapsulate a set of read-only properties. This explains
Why Type.GetFields returns an empty array when called on your anonymous type: anonymous types do not have public fields.
The public properties on an anonymous type are read-only and can not have their value set by a call to PropertyInfo.SetValue. If you call PropertyInfo.GetSetMethod on a property in an anonymous type, you will receive back null.
In fact, if you change
var properties = TypeDescriptor.GetProperties(sample);
while (nwReader.Read()) {
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyDescriptor info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
fdList.Add(obj);
}
to
PropertyInfo[] properties = sample.GetType().GetProperties();
while (nwReader.Read()) {
// No way to create a constructor so this call creates the object without calling a ctor. Could this be a source of the problem?
T obj = (T)FormatterServices.GetUninitializedObject(typeof(T));
foreach (PropertyInfo info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop will throw an exception as PropertyInfo.GetSetMethod fails
info.SetValue(obj, nwReader[i], null);
break;
}
}
}
fdList.Add(obj);
}
you will receive an exception informing you that the property set method can not be found.
Now, to solve your problem, what you can do is use Activator.CreateInstance. I'm sorry that I'm too lazy to type out the code for you, but the following will demonstrate how to use it.
var car = new { Make = "Honda", Model = "Civic", Year = 2008 };
var anothercar = Activator.CreateInstance(car.GetType(), new object[] { "Ford", "Focus", 2005 });
So just run through a loop, as you've done, to fill up the object array that you need to pass to Activator.CreateInstance and then call Activator.CreateInstance when the loop is done. Property order is important here as two anonymous types are the same if and only if they have the same number of properties with the same type and same name in the same order.
For more, see the MSDN page on anonymous types.
Lastly, and this is really an aside and not germane to your question, but the following code
foreach (PropertyDescriptor info in properties) {
for (int i = 0; i < nwReader.FieldCount; i++) {
if (info.Name == nwReader.GetName(i)) {
// This loop runs fine but there is no change to obj!!
info.SetValue(obj, nwReader[i]);
break;
}
}
}
could be simplified by
foreach (PropertyDescriptor info in properties) {
info.SetValue(obj, nwReader[info.Name]);
}
I had the same problem, I resolved it by creating a new Linq.Expression that's going to do the real job and compiling it into a lambda: here's my code for example:
I want to transform that call:
var customers = query.ToList(r => new
{
Id = r.Get<int>("Id"),
Name = r.Get<string>("Name"),
Age = r.Get<int>("Age"),
BirthDate = r.Get<DateTime?>("BirthDate"),
Bio = r.Get<string>("Bio"),
AccountBalance = r.Get<decimal?>("AccountBalance"),
});
to that call:
var customers = query.ToList(() => new
{
Id = default(int),
Name = default(string),
Age = default(int),
BirthDate = default(DateTime?),
Bio = default(string),
AccountBalance = default(decimal?)
});
and do the DataReader.Get things from the new method, the first method is:
public List<T> ToList<T>(FluentSelectQuery query, Func<IDataReader, T> mapper)
{
return ToList<T>(mapper, query.ToString(), query.Parameters);
}
I had to build an expression in the new method:
public List<T> ToList<T>(Expression<Func<T>> type, string sql, params object[] parameters)
{
var expression = (NewExpression)type.Body;
var constructor = expression.Constructor;
var members = expression.Members.ToList();
var dataReaderParam = Expression.Parameter(typeof(IDataReader));
var arguments = members.Select(member =>
{
var memberName = Expression.Constant(member.Name);
return Expression.Call(typeof(Utilities),
"Get",
new Type[] { ((PropertyInfo)member).PropertyType },
dataReaderParam, memberName);
}
).ToArray();
var body = Expression.New(constructor, arguments);
var mapper = Expression.Lambda<Func<IDataReader, T>>(body, dataReaderParam);
return ToList<T>(mapper.Compile(), sql, parameters);
}
Doing this that way, i can completely avoid the Activator.CreateInstance or the FormatterServices.GetUninitializedObject stuff, I bet it's a lot faster ;)
Question #2:
I don't really know, but I would tend to use Activator.CreateObject() instead of FormatterServices.GetUninitializedObject(), because your object might not be created properly. GetUninitializedObject() won't run a default constructor like CreateObject() will, and you don't necessarily know what's in the black box of T...
This method stores one line of a sql query in a variable of anonymous type. You have to pass a prototype to the method. If any property of the anonymous type can not be found within the sql query, it is filled with the prototype-value. C# creates constructors for its anonymous classes, the parameters have the same names as the (read-only) properties.
public static T GetValuesAs<T>(this SqlDataReader Reader, T prototype)
{
System.Reflection.ConstructorInfo constructor = prototype.GetType().GetConstructors()[0];
object[] paramValues = constructor.GetParameters().Select(
p => { try { return Reader[p.Name]; }
catch (Exception) { return prototype.GetType().GetProperty(p.Name).GetValue(prototype); } }
).ToArray();
return (T)prototype.GetType().GetConstructors()[0].Invoke(paramValues);
}

Categories