Background
I'm using EF and I have many tables. When I insert a new entity with navigation properties' content but without the id (I'm reading the content out of a xls file) I don't want to load all the navigation properties explicitly. This was too much code. So I tried a generic way:
private void loadExistingNavigationProperties<TEntity>(TEntity entityToInsert) where TEntity : class
{
Type type = typeof(TEntity);
var properties = type.GetProperties().Except(type.GetProperties().Where(x => x.Name.Contains("id")));
foreach (PropertyInfo property in properties)
{
if (property.PropertyType.FullName.Contains("MyNamespace"))
{
property.SetValue(entityToInsert, findNavigationProperty<???>(property.GetValue(entityToInsert)));
}
}
}
I have my entityToInsert
. I check all its properties if it has a navigation property (contains("MyNamespace")
). If this is true, the navigation property should be loaded (see below) and set.
private object findNavigationProperty<TNavigationProperty>(TNavigationProperty navigationPropertyValue) where TNavigationProperty : class
{
List<TNavigationProperty> navigationProperties = GetAllEntries<TNavigationProperty>();
foreach (var entity in navigationProperties)
{
if (propertiesAreEqual(entity, navigationPropertyValue))
{
return entity;
}
}
return navigationPropertyValue;
}
The current value of the navigation property attribute is passed. It contains all information like a name or something but not the id. First I'm getting all available navigation properties having that type. Then I'm searching if there is one property which has the same properties as the current one. Then this one is returned and set as the navigation property.
Problem
My problem is now how can I tell the method findNavigationProperty
that the generic type is the type, which the property's value has. So replacing the ???
with the type.
Aucun commentaire:
Enregistrer un commentaire