映射子类的外键

时间:2015-03-21 00:13:06

标签: c# asp.net-mvc entity-framework

我有以下抽象类:

public abstract class ClauseComponent
    {
        public int ClauseComponentId { get; set; }
        public abstract string[] Determinate(ClimateChart chart);
        public abstract List<ClauseComponent> GiveCorrectPath(ClimateChart chart);

        public abstract String GetHtmlCode(Boolean isYes);
        public virtual void Add(Boolean soort, ClauseComponent component)
        {
            throw new ApplicationException();
        }

        public ClauseComponent()
        {

        }
    }

Clause类继承自抽象类:

public class Clause : ClauseComponent
    {

        public virtual ClauseComponent YesClause { get; set; }
        public virtual ClauseComponent NoClause { get; set; }
        public String Name { get; private set; }

        public virtual Parameter Par1 { get; set; }
        public virtual Parameter Par2 { get; set; }
        public int Waarde { get; set; }
        public String Operator { get; set; }

        public Clause()
        {
        }

        public Clause(String name, Parameter par1, String op, int waarde)
        {
            this.Name = name;
            this.Par1 = par1;
            this.Operator = op;
            this.Waarde = waarde;
        }

        public Clause(String name, Parameter par1, Parameter par2)
        {
            this.Name = name;
            this.Par1 = par1;
            this.Par2 = par2;
        }
}

这是抽象类的映射器(我没有子类的映射器):

public ClauseComponentsMapper()
        {
            ToTable("ClauseComponents");

            // Primary key
            HasKey(c => c.ClauseComponentId);

            // Properties
            Property(c => c.ClauseComponentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        }

我的数据库中有这个:

Database values

现在我想为映射命名,我该如何实现? 我从来没有对抽象类和子类进行映射,所以我在这里有点蓝色。

1 个答案:

答案 0 :(得分:0)

一种方法是为映射列创建属性,并在映射类中使用映射列属性映射虚拟属性。

E.g。

public class Clause : ClauseComponent
{
    public int MyCustomPar1Id{ get; set; }

    [ForeignKey("MyCustomPar1Id")]
    public virtual Parameter Par1 { get; set; }       
}

或流利的Api:

modelBuilder.Entity<Clause >().HasRequired(p => p.Par1 ) // Or Optional
            .HasForeignKey(p => p.MyCustomPar1Id);