0

i write a Generic-Service that will do all my work für my Models to be saved in the database. Now i have a Problem when i have a Model with a list of Models in it.

I can't get the abstract type of the list item.

Any idea?

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
}
Sl0w
  • 3
  • 2

1 Answers1

0

You can check if the object is implementing the ICollection interface.

More information in this Question: How to determine if a type is a type of collection?

Community
  • 1
  • 1
Joanvo
  • 5,677
  • 2
  • 25
  • 35