gpt4 book ai didi

c# - Entity Framework 和抽象类

转载 作者:搜寻专家 更新时间:2023-10-30 20:26:39 24 4
gpt4 key购买 nike

我是 Entity Framework 的新手,想知道我想做的事情是否可行。

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

每个“MonitorField”都有一个名为“AMonitoringTool”的抽象类列表**

AMonitoringTool 允许其他开发人员通过在外部 DLL 中继承 AMonitoringTool 来创建自己的字段。

主要问题是应用程序不知道“MonitorField”中的真实类型,因此无法将我的对象保存在数据库中。

我有一个带有 DbSetMonitorEntity,但我无法保存我的 Monitor 列表,我收到此错误消息:

“抽象类型‘{...}。AMonitoringTool”没有映射后代,因此无法映射...”

我的第一个想法是在每个继承自“AMonitoringTool”的 DLL 中实现映射,但我不知道如何去做。

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>";
}
}

最佳答案

您似乎希望此库的使用者拥有他们自己的 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>();

关于c# - Entity Framework 和抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com