Являются ли виды, отображаемые в EF?
Обычно я запускаю тест конфигурации EF, который проверяет все таблицы.
Я также размещаю основной код, но он работает только в том случае, если первичный ключ содержит одно и только одно свойство с именем Id. Вы можете исправить это с помощью метода FirstOrDefault (вы можете посмотреть здесь, как его называть How do I use reflection to call a generic method?).
[TestMethod]
public void All()
{
var properties = typeof (Context).GetProperties().Where(p => IsSubclassOfRawGeneric(typeof(DbSet<>), p.PropertyType));
foreach (PropertyInfo property in properties)
{
Type entityType = property.PropertyType.GetGenericArguments()[0];
PropertyInfo idProperty = entityType.GetProperty("Id");
if (idProperty == null)
{
Console.WriteLine("Id property not found. Cannot check type configuration");
continue;
}
Type idPropertyType = idProperty.PropertyType;
DbSet dbSet = _context.Set(entityType);
if (idPropertyType == typeof(string))
{
try
{
dbSet.Find("A");
}
catch (Exception e)
{
throw new Exception("Cannot access to DbSet " + property.Name, e);
}
}
else if (idPropertyType == typeof (int))
{
try
{
dbSet.Find(1);
}
catch (Exception e)
{
throw new Exception("Cannot access to DbSet " + property.Name, e);
}
}
else
{
Console.WriteLine("Id property type not supported ('{0}'). Cannot check type configuration", idPropertyType.Name);
continue;
}
}
}
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}