Возвращенная динамика DbSet
на самом деле является просто оберткой вокруг реального DbSet
объекта, который вы можете просто привести к.Проблема, однако, в том, что тип DbSet
не может быть выведен без использования универсального метода .
. Следующее сработало бы, но, вероятно, наименее предпочтительно:
private IEnumerable<T> GetDbSetByTableName<T>(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<T>(dbset as IEnumerable<T>);
}
}
Теперь, чтобы обойти это, у нас есть по крайней мере два варианта:
- Создать интерфейс (со всеми необходимыми базовыми свойствами), который реализуется всеми
DbSet
s.,Таким образом, мы можем привести динамический объект без необходимости указывать тип при конвертации. - Возвращать
IEnumerable<dynamic>
, который можно кастовать на лету.
Опция 1
public interface IBaseProperties
{
int Id { get; set; }
string Name { get; set; }
}
public class MyTable : IBaseProperties
{
// Add these with either T4 templates or create partial class for each of these entities
public int Id { get; set; }
public string Name { get; set; }
}
private IEnumerable<IBaseProperties> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);
}
}
// ...
// Using it
// ...
var dynamicdbset = GetDbSetByTableName("MyTable");
int id = dynamicdbset.FirstOrDefault().Id;
Опция 2
private IEnumerable<dynamic> GetDbSetByTableName(string tableName)
{
System.Reflection.PropertyInfo[] properties = typeof(ClearGUIEntities).GetProperties();
var prop = properties.FirstOrDefault(p => p.Name == tableName + "s");
using (var db = new ClearGUIEntities())
{
var dbset = prop?.GetValue(db);
return new List<dynamic>(dbset as IEnumerable<dynamic>);
}
}
// ...
// At this point, you can basically access any property of this entity
// at the cost of type-safety
string id = dynamicdbset.FirstOrDefault().Id;
string name = dynamicdbset.FirstOrDefault().Name;
Кстати, приведение к List<T>
необходимо, потому что вы используете объект вне блока using
, в этот момент он был быраспоряжаться.
new List<IBaseProperties>(dbset as IEnumerable<IBaseProperties>);