【问题标题】:Entity Framwork. Generic entity method to add to any set type实体框架。添加到任何集合类型的通用实体方法
【发布时间】:2018-06-14 09:53:06
【问题描述】:

我试图弄清楚如何制作一个通用实体对象。我有大约 5 种不同的实体类型,它们具有共同的属性。

我创建了一个抽象类 TableBase & Interfaces,允许我处理实体的父级和子级:

    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 是特定类型的,只会让我将此对象添加到它的集合类型中。 我需要通过某种方式将它接受的对象类型添加到集合中。

【问题讨论】:

  • 为什么不像AddNode&lt;T&gt;那样向AddNode添加通用参数。在这种情况下,您可以传递所需的类型。
  • 我试过了。看看下面的结果
  • 你能发布一下 tblLine 是如何声明的吗?
  • 我已将其添加到问题@user1672994

标签: c# entity-framework generic-programming


【解决方案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;
}

【讨论】:

  • 它不会让我做一个新的 T 嘿。表示它没有新的约束
  • 我得到一个异常,只有特定类型的实体可以添加到 Set。并且不能向其中添加 TblBase 对象。
  • 对不起,我不知道
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 2012-10-28
  • 2011-05-17
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多