Would it be possible to create code like this:
private static string GetInsertString<TDto>()
{
var type = typeof(TDto);
var properties = type.GetProperties().Where(Where);
var tableName = type.Name;
return string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
tableName,
string.Join(",", properties.Select(x => x.Name).ToArray()),
string.Join(",", properties.Select(x => string.Format("@{0}", x.Name.ToLower())).ToArray()));
}
that works with anonymous types like this:
var point = new { X = 13, Y = 7 };
PS:
Output would be:
INSERT INTO Anonymous (X, Y) values (13, 7)
of course you may want to provide the table name.
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
The compiler gives them a name although your application cannot access it. 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.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.
You won't be able to specify the type parameter with an anonymous type, but if you pass it an object as a parameter, you can use type inference to get a hold of the type:
private static string GetInsertString<TDto>(TDto dto)
{
var type = typeof(TDto);
var propertyNames = type.GetProperties().Where(Where).Select(x => x.Name);
return string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
type.Name,
string.Join(",", propertyNames),
string.Join(",", propertyNames.Select(x => string.Format("@{0}", x.ToLower())));
}
Then call the method: var insertString = GetInsertString(new { X = 13, Y = 7 });
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