我有類似的問題,我想創建一個方法,從數據庫中給我的對象,所以創建了這段代碼。 我希望這可以幫助你:
要把它放到你的DatabaseContainer:
public IEnumerable<TEntity> Find<TEntity>(Dictionary<string, object> findValues = null) where TEntity : EntityObject
{
var entities = this.CreateObjectSet<TEntity>().ToList();
if (findValues!= null && findValues.Count > 0)
{
foreach (var item in findValues)
{
if(item.Value != null)
entities = entities.DynamicContains<TEntity>(item.Key, item.Value);
}
}
return entities;
}
,並把這個變成一個extention類:
public static List<TEntity> DynamicContains<TEntity>(this IEnumerable<TEntity> entities, string propertyName, object item)
{
List<TEntity> comparingEntities = new List<TEntity>();
foreach (var obj in entities)
{
var property = obj.GetType().GetProperty(propertyName);
if (property.PropertyType == typeof(String) && ((string)property.GetValue(obj, new object[] { })).ToLower().Contains(item.ToString().ToLower()))
comparingEntities.Add(obj);
if (property.PropertyType == typeof(Boolean) && ((bool)property.GetValue(obj, new object[] { })) == (bool)item)
comparingEntities.Add(obj);
}
return comparingEntities;
}
用法:
Dictionary<string, object> findValues = new Dictionary<string, object>();
findValues.Add("Name", "Tom");
findValues.Add("Age", 4);
var list1 = db.Find<Person>(findValues); // Returns a list of persons that includes the find values.
var list2 = db.Find<Person>() // Returns all persons in the database.
究竟是什麼你要?一個'ArrayList'?或者'數組'?或者是一個'List'?或者是其他東西? –
'DbSet'的超類'DbQuery'實現'IEnumerable',所以你可以把它轉換成它。 –
我想要清單或IEnumerable –
Rayet