简体   繁体   中英

code -first Entity framework - Is this possible with inheritance and navigation properties?

I haven't been able to figure this one out.

public abstract class A
{
    public int property1 { get; set; }
    public int property2 {get; set; }
}

public class B : A
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public IList<C> C { get; set; }

}

public class C : A
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AId { get; set; }

    public int dummyproperty {get; set; }

    public int BId { get; set; }

    [ForeignKey("BId")]
    public virtual B B { get; set; }
}

How can I have my database context build these 2 tables using these class B and C?

class Program
    {
        static void Main(string[] args)
        {
            var context = new MyContext();
            foreach(var b in context.Bs)
            {
                Console.WriteLine(b.ToString());
            }
        }
    }

    public class MyContext : DbContext
    {
        public DbSet<C> Cs { get; set; }
        public DbSet<B> Bs { get; set; }
    }

And then in Package Manager Console, run commands: enable-migrations add-migration Initial update-database

And then add some records for B and C in file 'Configuration.cs' method Seed.

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