is there any way how to actually get to the CSSpace in entity framework 6 code first?
I tried to convert DbContext to ObjectContext like this:
public static ObjectContext ToObjectContext(this DbContext dbContext)
{
return ((IObjectContextAdapter)dbContext).ObjectContext;
}
but how can I get access to the CSSpace via the ObjectContext?
thanks for answers, any help would be appreciated, I tried a lot but it seems that nothing works :/
I was having the same problem and came across a few links online which I tweaked and build the extension methods below. TableMapping and ColumnMapping are just simple classes I use to store the translation data, so you can just ignore those.
I adapted snippets of Måns Tånneryd code from his answer here
(half way down).
The biggest issue with CSSpace is that most of the information you need is not exposed. Thus the most useful part of this is the use of reflection to get array and property data. Hopefully, this help. feel free to ping me if you need any further explanation.
public static IEnumerable<TableMapping> GetMappings(this DbContext context)
{
List<TableMapping> tableMappings = new List<TableMapping>();
var storageMapping = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItem<GlobalItem>(((IObjectContextAdapter)context).ObjectContext.DefaultContainerName, DataSpace.CSSpace);
dynamic entitySetMaps = storageMapping.GetType().InvokeMember(
"EntitySetMaps",
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
null, storageMapping, null);
foreach (var entitySetMap in entitySetMaps)
{
var typeMappings = GetArrayList("EntityTypeMappings", entitySetMap);
dynamic typeMapping = typeMappings[0];
dynamic types = GetArrayList("Types", typeMapping);
var fragments = GetArrayList("MappingFragments", typeMapping);
var fragment = fragments[0];
var tableSet = GetProperty("TableSet", fragment);
var tableName = GetProperty("Name", tableSet);
TableMapping tm = new TableMapping
{
Entity = context.FindContextTableName((string)types[0].Name),
Table = tableName
};
var properties = GetArrayList("AllProperties", fragment);
List<ColumnMapping> columnMappings = new List<ColumnMapping>();
foreach (var property in properties)
{
var edmProperty = GetProperty("EdmProperty", property);
var columnProperty = GetProperty("ColumnProperty", property);
ColumnMapping cm = new ColumnMapping
{
Property = edmProperty.Name,
Column = columnProperty.Name
};
columnMappings.Add(cm);
}
tm.Columns = columnMappings.AsEnumerable();
tableMappings.Add(tm);
}
return tableMappings.AsEnumerable();
}
private static ArrayList GetArrayList(string property, object instance)
{
var type = instance.GetType();
var objects = (IEnumerable)type.InvokeMember(
property,
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, instance, null);
var list = new ArrayList();
foreach (var o in objects)
{
list.Add(o);
}
return list;
}
private static dynamic GetProperty(string property, object instance)
{
var type = instance.GetType();
return type.InvokeMember(property, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, instance, null);
}
Related
I have provided a dotnetfiddle to show the issue.
I try to copy object from a source that have the same property names and type except some properties that have IEnumerable and target object has
IList using reflection.
public T CopyTo<T>(object src)
where T : new()
{
var targetObj = new T();
//Getting Type of Src
var sourceType = src.GetType();
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty;
var sourcePi = sourceType.GetProperties(flags);
foreach (var property in sourcePi)
{
var pi = targetObj.GetType().GetProperty(property.Name);
if (pi == null || !pi.CanWrite)
continue;
object sourceValue = property.GetValue(src, null);
//var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);
//this works, but hard wired
if (sourceValue is IEnumerable<string> i)
sourceValue = ((IEnumerable<string>)i).Cast<string>().ToList();
pi.SetValue(targetObj, sourceValue, null);
}
return targetObj;
}
It raises an error:
System.ArgumentException: 'Object of type 'System.String[]' cannot be
converted to type 'System.Collections.Generic.List`1[System.String]'.'
I tried to convert:
var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);
but also get error
System.InvalidCastException: Object must implement IConvertible.
this issue can't help.
My workaround solution is casting :
sourceValue = ((IEnumerable<string>) sourceValue).Cast<string>().ToList();
The disadvantage is hard wiring the cast to IEnumerable<string>
Is there a better way to copy IEnumerable<T> to IList<T> or any generic collection using reflection.
A simple approach would be to check if IEnumerable<T> is assignable from the source property's type, check if the destination property's type is assignable from List<T>, and if so then assign a new List<T> to the destination property passing the source property's value into the constructor.
public T CopyTo<T>(object src) where T : new()
{
var targetObj = new T();
var sourceType = src.GetType();
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty;
var sourcePi = sourceType.GetProperties(flags);
foreach (var property in sourcePi)
{
var pi = targetObj.GetType().GetProperty(property.Name);
if (pi == null || !pi.CanWrite)
continue;
object sourceValue = property.GetValue(src, null);
//var sourceValue = Convert.ChangeType(property.GetValue(src, null), pi.PropertyType);
//this works, but hard wired
if (property.PropertyType.IsGenericType)
{
Type enumerable = typeof(IEnumerable<>).MakeGenericType(property.PropertyType.GenericTypeArguments);
if (enumerable.IsAssignableFrom(property.PropertyType))
{
Type list = typeof(List<>).MakeGenericType(property.PropertyType.GenericTypeArguments);
if (pi.PropertyType.IsAssignableFrom(list))
{
var pValue = Activator.CreateInstance(list, new[] { sourceValue });
pi.SetValue(targetObj, pValue, null);
}
}
}
else
{
pi.SetValue(targetObj, sourceValue, null);
}
}
return targetObj;
}
It isn't hard to imagine situations where this wouldn't work... for example if the destination type's property is LinkedList<T> or T[] then the properties won't copy. You'd have to modify it further to handle cases like this.
This would also create a new List<T> for the destination object even if the properties on the two objects are both exactly the same type. It isn't clear if that is what you want or not, but it is different from how other properties are copied by this method so it is worth mentioning.
I think you need to add a check of the destination type too.
And then, With the two different type (source and destination),
You can create a function that will handle the conversion/cast.
Something like this:
1. Source IEnumerable<T>, Destination: List<T> => Create New list and put in CTOR
2. Source List<T>, Destination: List<T> => Just Copy
3. Source List<T>, Destination: IEnumerable<T> => Create a list
4. Source IEnumerable<T> ,Destination: IEnumerable<T> => Made a copy?
I would like to assign values to various classes. How I would achieve the code below would work?
T row = new T();
row[propertyName1] = "value 1";
row[propertyName2] = "value 2";
row[propertyName3] = "value 3";
I have various classes. I have property names for each class with values.
What I am trying to do is to assign all table values from database to classes Lists. All classes in C# are exact match to tables in SQL. Entitiy framework do this. I would like to build the same functionality as EF do.
You can use such thing using reflexion:
using System.Reflection;
static void Test()
{
var list = new List<int>();
list.SetProperty("Capacity", 10);
}
static BindingFlags DefaultBindingFlags
= BindingFlags.Public
| BindingFlags.Static
| BindingFlags.Instance;
static void SetProperty<T>(this T instance, string name, object value)
//where T : ...
{
PropertyInfo p = instance.GetType().GetProperty("Capacity", DefaultBindingFlags);
if ( p != null )
p.SetValue(instance, value, null);
else
throw new Exception($"Property {name} doesn't exist.");
}
I am trying to create a run-time mock, which will have a specific behaviour for every method, which will be called. For example this mock should always return null - which is already working - or raise an exception for a not reachable database or in this specific case throw an Argument Exception.
I know, that this could be done fairly easy with a mocking framework. But since I have to use this via Spring.NET, I can not use a mocking framework, as far as I know. This is because I have to give a type into the StaticApplicationContext. If there is an easier way to create mock types, let me know.
The code below will throw an Expected:
But was: (Common Language Runtime detected an invalid program.)
at TypeMock.Foo()
at TypeBuilderTest.
public interface IInterfaceWithObject
{
String Foo();
}
[Test]
public void MinimalExample()
{
//build expression
var constructorInfo = typeof(ArgumentNullException).GetConstructor(new Type[0]);
Assert.IsNotNull(constructorInfo);
Expression expression = Expression.Throw(Expression.New(constructorInfo));
//create type
// based upon https://stackoverflow.com/questions/38345486/dynamically-create-a-class-by-interface
var ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.Run);
var mb = ab.DefineDynamicModule("Test");
TypeBuilder typeBuilder = mb.DefineType("TypeMock");
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
typeBuilder.AddInterfaceImplementation(typeof(IInterfaceWithObject));
List<MethodInfo> methods = new List<MethodInfo>(typeof(IInterfaceWithObject).GetMethods());
foreach (Type interf in typeof(IInterfaceWithObject).GetInterfaces())
{
foreach (MethodInfo method in interf.GetMethods())
if (!methods.Contains(method))
methods.Add(method);
}
foreach (var imethod in methods)
{
var parameters = imethod.GetParameters();
List<Type> parameterTypes = new List<Type>();
foreach (var parameter in parameters)
{
parameterTypes.Add(parameter.ParameterType);
}
var method =
typeBuilder.DefineMethod
(
"##" + imethod.Name,
MethodAttributes.Public | MethodAttributes.Static,
imethod.ReturnType,
parameterTypes.ToArray()
);
var thisParameter = Expression.Parameter(typeof(IInterfaceWithObject), "this");
var bodyExpression = Expression.Lambda
(expression
,
thisParameter
);
bodyExpression.CompileToMethod(method);
var stub =
typeBuilder.DefineMethod(imethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, imethod.ReturnType, parameterTypes.ToArray());
var il = stub.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Call, method, null);
il.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(stub, imethod);
}
Type type = typeBuilder.CreateType();
//create instance via spring.net
StaticApplicationContext context = new StaticApplicationContext();
MutablePropertyValues value = new MutablePropertyValues();
string objectName = "Integer";
context.RegisterSingleton(objectName, type, value);
var objectInstance = (IInterfaceWithObject)context.GetObject(objectName);
Assert.Throws<ArgumentNullException>(() => objectInstance.Foo());
}
I'm trying to populate a generic List< T > from another List< U > where the field names match, something like the untested pseudocode below. Where I'm having problems is when T is a string, for instance, which has no parameterless constructor. I've tried adding a string directly to the result object, but this gives me the obvious error -- that a string is not of Type T. Any ideas of how to solve this issue? Thanks for any pointers.
public static List<T> GetObjectList<T, U>(List<U> givenObjects)
{
var result = new List<T>();
//Get the two object types so we can compare them.
Type returnType = typeof(T);
PropertyInfo[] classFieldsOfReturnType = returnType.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
Type givenType = typeof(U);
PropertyInfo[] classFieldsOfGivenType = givenType.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
//Go through each object to extract values
foreach (var givenObject in givenObjects)
{
foreach (var field in classFieldsOfReturnType)
{
//Find where names match
var givenTypeField = classFieldsOfGivenType.Where(w => w.Name == field.Name).FirstOrDefault();
if (givenTypeField != null)
{
//Set the value of the given object to the return object
var instance = Activator.CreateInstance<T>();
var value = field.GetValue(givenObject);
PropertyInfo pi = returnType.GetProperty(field.Name);
pi.SetValue(instance, value);
result.Add(instance);
}
}
}
return result;
}
If T is string and you have already created custom code to convert your givenObject to a string, you just need to do an intermediate cast to object to add it to a List<T>:
public static List<T> GetObjectList2<T, U>(List<U> givenObjects) where T : class
{
var result = new List<T>();
if (typeof(T) == typeof(string))
{
foreach (var givenObject in givenObjects)
{
var instance = givenObject.ToString(); // Your custom conversion to string.
result.Add((T)(object)instance);
}
}
else
{
// Proceed as before
}
return result;
}
Incidentally, you are adding an instance of T to result for every property of T that matches a property name in U and for every item in givenObjects. I.e. if givenObjects is a list of length 1 and T is a class with 10 matching properties, result could end up with 10 entries. This looks wrong. Also, you need to watch out for indexed properties.
As an alternative to this approach, consider using Automapper, or serializing your List<U> to JSON with Json.NET then deserializing as a List<T>.
How can I check for db null values in the attached code? Please understand I am a new C# convert...
What this code does is takes a IDataReader object and converts and maps it to a strongly-typed list of objects. But what I am finding is it completely errors out when there are null columns returned in the reader.
Converter
internal class Converter<T> where T : new()
{
// Declare our _converter delegate
readonly Func<IDataReader, T> _converter;
// Declare our internal dataReader
readonly IDataReader dataReader;
// Build our mapping based on the properties in the class/type we've passed in to the class
private Func<IDataReader, T> GetMapFunc()
{
// declare our field count
int _fc = dataReader.FieldCount;
// declare our expression list
List<Expression> exps = new List<Expression>();
// build our parameters for the expression tree
ParameterExpression paramExp = Expression.Parameter(typeof(IDataRecord), "o7thDR");
ParameterExpression targetExp = Expression.Variable(typeof(T));
// Add our expression tree assignment to the exp list
exps.Add(Expression.Assign(targetExp, Expression.New(targetExp.Type)));
//does int based lookup
PropertyInfo indexerInfo = typeof(IDataRecord).GetProperty("Item", new[] { typeof(int) });
// grab a collection of column names from our data reader
var columnNames = Enumerable.Range(0, _fc).Select(i => new { i, name = dataReader.GetName(i) }).AsParallel();
// loop through all our columns and map them properly
foreach (var column in columnNames)
{
// grab our column property
PropertyInfo property = targetExp.Type.GetProperty(column.name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
// check if it's null or not
if (property != null)
{
// build our expression tree to map the column to the T
ConstantExpression columnNameExp = Expression.Constant(column.i);
IndexExpression propertyExp = Expression.MakeIndex(paramExp, indexerInfo, new[] { columnNameExp });
UnaryExpression convertExp = Expression.Convert(propertyExp, property.PropertyType);
BinaryExpression bindExp = Expression.Assign(Expression.Property(targetExp, property), convertExp);
// add it to our expression list
exps.Add(bindExp);
}
}
// add the originating map to our expression list
exps.Add(targetExp);
// return a compiled cached map
return Expression.Lambda<Func<IDataReader, T>>(Expression.Block(new[] { targetExp }, exps), paramExp).Compile();
}
// initialize
internal Converter(IDataReader dataReader)
{
// initialize the internal datareader
this.dataReader = dataReader;
// build our map
_converter = GetMapFunc();
}
// create and map each column to it's respective object
internal T CreateItemFromRow()
{
return _converter(dataReader);
}
}
Mapper
private static IList<T> Map<T>(DbDataReader dr) where T : new()
{
try
{
// initialize our returnable list
List<T> list = new List<T>();
// fire up the lamda mapping
var converter = new Converter<T>(dr);
while (dr.Read())
{
// read in each row, and properly map it to our T object
var obj = converter.CreateItemFromRow();
// add it to our list
list.Add(obj);
}
// reutrn it
return list;
}
catch (Exception ex)
{
// make sure this method returns a default List
return default(List<T>);
}
}
I just don't quite understand where the column to typed object happens in here, so I'd try to do it myself... but I just don;t know where it is.
I know this probably won't help much, but the error I am getting is:
Unable to cast object of type 'System.DBNull' to type 'System.String'.
and it happens on the
internal T CreateItemFromRow()
{
return _converter(dataReader); //<-- Here
}
Note
This does not happen if I wrap the columns in the query itself with an ISNULL(column, ''), but I am sure you can understand that this is surely not a solution
The problem lies in the line convertExp = Expression.Convert(propertyExp, property.PropertyType). You can't expect to convert DbNull value to its equivalent in framework type. This is especially nasty when your type is a value type. One option is to check if the read value from db is DbNull.Value and in case yes, you need to find a compatible value yourself. In some cases people are ok with default values of those types in C#. If you have to do this
property = value == DBNull.Value ? default(T): value;
a generic implementation would look like (as far as the foreach in your converter class goes):
foreach (var column in columns)
{
var property = targetExp.Type.GetProperty(
column.name,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (property == null)
continue;
var columnIndexExp = Expression.Constant(column.i);
var propertyExp = Expression.MakeIndex(
paramExp, indexerInfo, new[] { columnIndexExp });
var convertExp = Expression.Condition(
Expression.Equal(
propertyExp,
Expression.Constant(DBNull.Value)),
Expression.Default(property.PropertyType),
Expression.Convert(propertyExp, property.PropertyType));
var bindExp = Expression.Assign(
Expression.Property(targetExp, property), convertExp);
exps.Add(bindExp);
}
Now this does an equivalent of
property = reader[index] == DBNull.Value ? default(T): reader[index];
You could avoid the double lookup of the reader by assigning it to a variable and using its value in the conditional check. So this should be marginally better, but a lil' more complex:
foreach (var column in columns)
{
var property = targetExp.Type.GetProperty(
column.name,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (property == null)
continue;
var columnIndexExp = Expression.Constant(column.i);
var cellExp = Expression.MakeIndex(
paramExp, indexerInfo, new[] { columnIndexExp });
var cellValueExp = Expression.Variable(typeof(object), "o7thPropValue");
var convertExp = Expression.Condition(
Expression.Equal(
cellValueExp,
Expression.Constant(DBNull.Value)),
Expression.Default(property.PropertyType),
Expression.Convert(cellValueExp, property.PropertyType));
var cellValueReadExp = Expression.Block(new[] { cellValueExp },
Expression.Assign(cellValueExp, cellExp), convertExp);
var bindExp = Expression.Assign(
Expression.Property(targetExp, property), cellValueReadExp);
exps.Add(bindExp);
}
This does the conditional check this way:
value = reader[index];
property = value == DBNull.Value ? default(T): value;
This is one of the most annoying problems in dealing with datasets in general.
The way I normally get around it is to convert the DBNull value to something more useful, like an actual null or even a blank string in some cases. This can be done in a number of ways, but just recently I've taken to using extension methods.
public static T? GetValueOrNull<T>(this object value) where T : struct
{
return value == null || value == DBNull.Value ? (T?) null : (T) Convert.ChangeType(value, typeof (T));
}
A handy extension method for nullable types, so for example:
int? myInt = DataSet.Tables[0].Rows[0]["DBNullInt"].GetValueOrNull<int>();
Or a more generic one to just convert a DBNull in to a null:
public static object GetValueOrNull(this object value)
{
return value == DBNull.Value ? null : value;
}
string myString DataSet.Tables[0].Rows[0]["DBNullString"].GetValueOrNull();
You'll then get a null string, rather than trying to put a DBNull in to a string.
Hopefully that may help you a little.
As I come across this problem recently
both
Expression.TypeIs(propertyExp,typeof(DBNull));
and
Expression.Equal(propertyExp,Expression.Constant(DBNull.Value));
didn't work for me as they did increase memory allocation (which is my primary concern in this case)
here is the benchmark for both mapper approach compare to Dapper on 10K rows query.
TypeIs
and
Equal
so to fix this problem it came out that an IDataRecord is able to call "IsDBNull" to check whether the column in current reader is DBNull or not
and can be write as expression like
var isReaderDbNull = Expression.Call(paramExp, "IsDBNull", null, readerIndex);
finally, I end up with this solution
and now the performance is acceptable again.