我写了一个通用服务,它将我的模型的所有工作都保存在数据库中。 现在我有一个问题,当我有一个模型列表中的模型。
我无法获得列表项的抽象类型。
有什么想法吗?
public abstract class AbstractEntity
{
[Key]
public virtual int Id
{
get;
set;
}
}
public class Invoice : AbstractEntity
{
public int ContactId
{
get;
set;
}
public virtual Contact ContactInformation
{
get;
set;
}
public virtual ObservableCollection<Position> Positions
{
get;
set;
}
public DateTime? BillingDate
{
get;
set;
}
public string Number
{
get;
set;
}
public double Sum
{
get;
set;
}
}
public abstract class AbstractService<T>: IDisposable where T : AbstractEntity
{
#region Fields
protected Context _context;
#endregion
public virtual void Add(params T[] items)
{
foreach (T item in items)
{
SetState(item, EntityState.Added);
}
}
public virtual void Update(params T[] items)
{
foreach (T item in items)
{
SetState(item, EntityState.Modified);
}
}
public virtual void Remove(params T[] items)
{
foreach (T item in items)
{
SetState(item, EntityState.Deleted);
}
}
public int SaveChanges()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
#endregion
#region Private Methodes
private void SetState(AbstractEntity Object, EntityState state)
{
if (Object.Id != null)
_context.Entry(Object).State = state;
else
_context.Entry(Object).State = EntityState.Added;
Type objType = Object.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (var prop in properties)
{
if ((prop.PropertyType.BaseType == typeof(AbstractEntity)))
{
var entity = prop.GetValue(Object, null);
if (entity is AbstractEntity)
SetState((AbstractEntity)entity, state);
} else
if (prop.PropertyType.BaseType == typeof(Collection<???>)) <=== Problem here
{
var entity = prop.GetValue(Object, null);
foreach (var pos in (Collection<???>)entity) <=== and here
{
SetState(pos, state);
}
}
}
}
#endregion
}
答案 0 :(得分:0)
您可以检查对象是否正在实施ICollection
界面。
本课题中的更多信息:How to determine if a type is a type of collection?