实现接口导致TPT从继承类导致TPH

时间:2015-06-29 21:19:01

标签: ef-code-first entity-framework-6

我想创建一个自引用文件夹表和相关的文件表

如MyFolder1和MyFile1所示。

enter image description here

我了解如何通过继承接口来获得此结构。

是否也可以通过继承抽象类来实现?

public class Model1Context : DbContext
{
    public Model1Context()
        : base("name=Model1")
    {
        Database.SetInitializer(new Model1Initializer());
    }

    public virtual DbSet<MyFolder1> MyFolder1s { get; set; }
    public virtual DbSet<MyFile1> MyFile1s { get; set; }
    public virtual DbSet<MyFolder2> MyFolder2s { get; set; }
    public virtual DbSet<MyFile2> MyFile2s { get; set; }
}

public class Model1Initializer : DropCreateDatabaseIfModelChanges<Model1Context>
{
}

public class MyFolder1 : BasicBO, ISequencedTreeNode
{
    public MyFolder1 MyFolder { get; set; }
    public int SeqNo { get; set; }
    [NotMapped]
    public ISequencedTreeNode Parent
    {
        get
        {
            return MyFolder;
        }
        set
        {
            MyFolder = (MyFolder1)value;
        }
    }
}

public class MyFile1 : BasicBO, ISequencedTreeNode
{
    public MyFolder1 MyFolder { get; set; }
    public int SeqNo { get; set; }
    [NotMapped]
    public ISequencedTreeNode Parent
    {
        get
        {
            return MyFolder;
        }
        set
        {
            MyFolder = (MyFolder1)value;
        }
    }
}

public interface ISequencedTreeNode
{
    [Required]
    int SeqNo { get; set; }
    ISequencedTreeNode Parent { get; set; }
}

public abstract class SequencedTreeNode : BasicBO
{
    [Required]
    public  int SeqNo { get; set; }
    public  SequencedTreeNode Parent { get; set; }
}

//  [Table("MyFolder2")]
public class MyFolder2 : SequencedTreeNode
{

}

//  [Table("MyFile2")]
public class MyFile2 : SequencedTreeNode
{

}

public class BasicBO
{
    public int Id { get; set; }
    public string Name { get; set; }
}

将BasicBO标记为抽象似乎不会影响表构造。

[更新] 我可以通过向MyFile2和MyFolder2添加[Table(&#39; tablename&#39;)]属性来强制TPT,但是这些表将只有一个Id字段,而SequencedTreeNodes表仍然会创建。

对我来说,一个接口在强制TPT方面可能更有效是有道理的,因为总是需要为接口实现属性。但是,如果我在SequencedTreeNode摘要中创建所有属性,我会认为会发生同样的事情。但是,如果我这样做,我会收到运行时错误&#39;属性&#39; SeqNo&#39;不是类型&#39; MyFile2&#39;&#39;

的声明属性

0 个答案:

没有答案