C# 实体框架。要添加到任何集合类型的泛型实体方法
我试图找出如何创建一个通用实体对象。我有大约5种不同的实体类型,它们共享公共属性 我创建了一个抽象类TableBase&Interfaces,允许我处理实体的父级和子级:C# 实体框架。要添加到任何集合类型的泛型实体方法,c#,entity-framework,generic-programming,C#,Entity Framework,Generic Programming,我试图找出如何创建一个通用实体对象。我有大约5种不同的实体类型,它们共享公共属性 我创建了一个抽象类TableBase&Interfaces,允许我处理实体的父级和子级: public interface IHasChildren { IEnumerable<object> Children { get; } } public interface IHasParent{ Object Parent { get; } } public abstract cl
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; }
}
正如您所看到的,这里的问题是,NewNode是特定于类型的,并且只允许我将此对象添加到其集合类型中。
我需要找到一种方法,用它可以接受的对象类型添加到集合中。您考虑过将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;
}
公共静态bool AddNode(ProjectEntities DBContext,LocalUser User,T ParentEntity),其中T:TblBase,new()
{
var BaseEntity=(TblBase)ParentEntity;
var ChildType=((IHasChildren)ParentEntity).Children.GetType().GetGenericArguments()[0];
T NewNode=newt
{
ParentID=BaseEntity.ID,
COID=User.ID,
IsSelected=true,
IsExpanded=true
};
DBContext.Set().Add(NewNode);
//如果没有进一步的操作,可能需要在此处调用DBContext.SaveChanges()
返回true;
}
为什么不像
AddNode
那样向AddNode添加泛型参数呢。在这种情况下,您可以传递所需的类型。我已经尝试过了。看看下面的结果,你能发布一下tblLine是如何声明的吗?我已经把它添加到问题@user1672994中了,它不会让我做一个新的t hey。表示它没有新的约束。我得到一个异常,即只有特定类型的实体才能添加到集合中。而且TblBase对象无法添加到其中。很抱歉,我不知道
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;
}