简体   繁体   中英

Mapping foreign keys of subclasses

I have following abstract class:

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()
        {

        }
    }

The Clause class inherits from the abstract class:

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

This is the mapper of the abstract class (I dont have a mapper for the subclass):

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

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

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

        }

I have this in my DB:

数据库值

Now I want to give a proper name to the mapping, how can I accomplish this? I have never done the mapping on abstract classes and subclasses so I'm a little bit in the blue here.

One way is to create properties for the mapping columns, and in the mapping class, map the virtual property using the mapping column property.

Eg

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

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

Or Fluent Api:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM