2015-06-09 89 views
2

我是新来的实体框架,想知道我想做什么,是可能的。实体框架和抽象类

我有一个名为'Monitor'的类,其中包含'MonitorField'的列表。

每个“MonitorField”有一个名为“AMonitoringTool” **抽象类的List

AMonitoringTool是提供允许其他开发人员创建自己的领域的一种,由继承AMonitoringTool在外部DLL中。

主要问题是应用程序不知道'MonitorField'中的实际类型,防止将我的对象保存在数据库中。

我有一个MonitorEntityDbSet,但我不能挽救我的监视名单,我得到这个错误信息:

“的抽象类型“{...} AMonitoringTool “没有映射后代,因此不能被映射......”

我首先想到的是要落实在每一个继承DLL映射‘AMonitoringTool’,但我不如何做到这一点。

MonitorEntity.cs

public class MonitorEntity : DbContext 
{ 
    public DbSet<Monitor> Monitors { get; set; } 

    public MonitorEntity() 
    { 

    } 
} 

Monitor.cs

public class Monitor 
    { 
     public Monitor(string name) 
     { 
      MonitorName = name; 
      FieldList = new List<MonitorField>(); 
     } 

     private List<MonitorField> m_fieldList = null; 
     public virtual List<MonitorField> FieldList 
     { 
      get 
      { 
       return m_fieldList; 
      } 
      set 
      { 
       m_fieldList = value; 
      } 
     } 
    } 

MonitorField.cs

public class MonitorField 
{ 
    public AMonitoringTool Configuration { get; set; } 

    public MonitorField() 
    { 
     FieldName = "<label>"; 
    } 
} 
+1

那么你需要要保存到数据库的具体类型,可以使上下文采用泛型类型参数。 – DavidG

+0

你可能有更好的运气将这样的动态保存到文档数据库中。您也可以将您的MonitorField项目序列化为字符串。 – CuddleBunny

回答

2

你似乎想CON这个库的sumers有自己的实现什么AMonitoringTool是。我建议你用泛型类型参数创建你的上下文,让消费者决定它是什么。像这样的东西应该工作:

//This isn't strictly needed but it will let you force some 
//Specific fields for the monitoring tool if you like 
public interface IMonitoringTool 
{ 
    string ForcedProperty { get; set; } 
} 

//Here the type parameter get used for the Configuration property: 
public class MonitorField<T> where T : IMonitoringTool 
{ 
    public T Configuration { get; set; } 
    public string FieldName { get; set; } 

    public MonitorField() 
    { 
     FieldName = "<label>"; 
    } 
} 

//And this is the context: 
public class MonitorEntity<T> : DbContext where T : IMonitoringTool 
{ 
    public DbSet<Monitor<T>> Monitors { get; set; } 
} 

public class Monitor<T> where T : IMonitoringTool 
{ 
    public Monitor(string name) 
    { 
     MonitorName = name; 
     FieldList = new List<MonitorField<T>>(); 
    } 

    public string MonitorName { get; set; } 
    public List<MonitorField<T>> FieldList { get; set; } 

} 

所以,现在如果一个消费者想要一个方面,他们建立自己的等级:

public MyMonitoringTool : IMonitoringTool 
{ 
    public string ForcedProperty { get; set; } 
    public string MyCustomProperty { get; set; } 
} 

并创建自己的背景:

var myContext = new MonitorEntity<MyMonitoringTool>(); 
+0

Thx为您的答案!我仍然有疑问,只有在单个监视器中的每个MonitorField包含从AMonitoringTool继承的相同类型时,您的解决方案才能工作? – Morgan

+0

另一位消费者可以用他们自己的监控字段实现创建一个单独的数据库,但每个数据库一旦被创建就会被锁定。 – DavidG

+0

好的,谢谢! – Morgan