我正在使用EF6读写规则以对SQLite DB进行某些验证。代码优先方法。我成功地将规则写到了DB。在我现在尝试阅读它们时,尽管数据库已正确镜像,但包含子规则的复杂规则似乎具有空的子规则列表。那里怎么了?
类层次结构是: 抽象规则-具有“验证”方法的抽象类。 abstract ComplexRule:规则-可以具有子规则的规则 SuperRule,OrRule和AndRule:ComplexRule实现 BasicRule:规则-直接执行,可以进行某些模式匹配。
DB中写出的表是这样的:
RuleId,Condition,Value,Mode,Discriminator,ComplexRule_RuleId
1,,,,SuperRule,
2,*USA*,*PATT1*,1,BasicRule,1
3,*CHN*,*PATT2*,1,BasicRule,1
读取代码如下:
using (var db = new RuleModel())
{
var q = db.Rules.OfType<SuperRule>).FirstOrDefault();
}
它产生一个SuperRule,其中子级为空。 db.Rules包含所有3条规则,但是BasicRule和SuperRule之间没有关联。
RuleModel(DbContext)如下:
public class RuleModel : DbContext
{
public RuleModel() : base("name=RuleModel")
{
}
public virtual DbSet<Rule> Rules { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RuleModel>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer);
}
}
规则如下:
public abstract class Rule
{
[Key]
public int RuleId { get; set; }
public abstract RuleResult Match(Mapping m);
}
public abstract class ComplexRule: Rule
{
public IList<Rule> ChildRules { set; get; }
public ComplexRule()
{
ChildRules = new List<Rule>();
}
}
public class OrRule : ComplexRule
{
public override RuleResult Match(Mapping m)
{
// Some logics
}
public OrRule() : base() { }
}
public class SuperRule: OrRule
{
public override RuleResult Match(Mapping m)
{
//some logics
}
public SuperRule() : base()
{
}
}
public class BasicRule : Rule
{
public string Condition { set; get; }
public string Value { set; get; }
public RuleMode Mode { set; get; }
public BasicRule(string condition, string value, RuleMode mode = RuleMode.MODE_ANYWHERE)
{
Condition = condition;
Value = value;
Mode = mode;
}
public BasicRule() { }
public override RuleResult Match(Mapping m)
{
// logics
}
}