How to configure one to many relationship along with inheritance in entityframework

1k Views Asked by At

I am working on entity framework code first pattern. I have one scenario where i have following entities,

public class Toy
{
public int ID {get; set;}
public string Name {get; set;}
}

for the above entity, all model building configuration has been done and table was created fine.

We have another entity,

public class Kid
{
public string Name {get; set;}
}

For this entity also, all model building configuration has been done and table was craeted fine in database.

Now i need to maintain/configure, one -many relationship between kid and toys i.e. one kid can have multiple toys

so i have create one custom class which will inherit Kid class,

public class KidToy : Kid
{
public virtual List<Toy> Toys{get; set;}
}

Note: I can't add List Toys property directly in Kid class, i am getting circular refernce error.

builder.Entity<Kid>().Map<KidToy>(m => {

            });

            builder.Entity<KidToy>().HasMany(b => b.Toys).WithMany().Map(b =>
            {
                b.MapLeftKey(KidId");
                b.MapRightKey("ToyId");
                b.ToTable("kidToyMap");
            });

I dont need table creation for the custom model class (KidToy) and i need to configure one-many relationship. Could you please guide me.

1

There are 1 best solutions below

1
On

use this :

public class Toy
{
    public int ID { get; set; }
    public string Name { get; set; }

    public int KidID { get; set; }

    [ForeignKey("KidID")]
    [InverseProperty("Toys")]
    public virtual Kid Kid { get; set; }
}

public class Kid
{
    public string Name { get; set; }

    [InverseProperty("Kid")]
    public virtual ICollection<Toy> Toys { get; set; }
}