实体框架。要添加到任何集类型的通用实体方法

时间:2018-06-14 09:53:07

标签: c# entity-framework generic-programming

我试图找出如何制作通用实体Object。我有大约5种不同的实体类型,它们共享共同的属性。

我创建了一个抽象类TableBase&允许我解决实体的界面'父母与父母小孩:

    public interface IHasChildren
{
    IEnumerable<object> Children { get; }
}

public interface IHasParent{
    Object Parent { get; }
}

public abstract class TblBase : INotifyPropertyChanged
{
  ....
      properties such as 
      int ParentID
      int COID
      bool IsSelected
      bool IsExpanded
  ....
 }

//tblLine is one of my 5 entity type classes which build up a hierarchy
       public partial class tblLine : TblBase, IHasChildren, IHasParent
        {
            public virtual ObservableCollection<tblGroup> tblGroups { get; set; }
            public virtual tblProject tblProject { get; set; }
        }

此处是我的代码:

    public static bool AddNode(ProjectEntities DBContext, LocalUser User, object ParentEntity)
    {
        var BaseEntity = (TblBase)ParentEntity;
        var ChildType = ((IHasChildren)ParentEntity).Children.GetType().GetGenericArguments()[0];

        Object NewNode = new tblLine
        {
            ParentID = BaseEntity.ID,
            COID = User.ID,
            IsSelected = true,
            IsExpanded = true
        } as object;

         DBContext.Set(ChildType).Add(NewNode);

        return true;
    }

此处的问题如您所见,NewNode是特定于类型的,只允许我将此对象添加到其集类型中。 我需要实现一些方法来添加一个它可以接受的对象类型。

1 个答案:

答案 0 :(得分:1)

您是否考虑过将AddNode()设为通用方法?

public static bool AddNode<T>(ProjectEntities DBContext, LocalUser User, T ParentEntity) where T:TblBase, new()
{
    var BaseEntity = (TblBase)ParentEntity;
    var ChildType = ((IHasChildren)ParentEntity).Children.GetType().GetGenericArguments()[0];

    T NewNode = new T
    {
        ParentID = BaseEntity.ID,
        COID = User.ID,
        IsSelected = true,
        IsExpanded = true
    };

     DBContext.Set<T>().Add(NewNode);
//may want to call DBContext.SaveChanges() here if no further actions to be taken
    return true;
}