Entity Framework Core many to many design problem

Viewed 125

the idea is that some kind of entity may have many images and images may be linked to many entities. In addition each many-to-many relationship has a number for an ordering position. So here is what my code looks like:

public abstract class X {
    public int Id{get; private set;}
    public ICollection<ImageLink> ImageLinks{ get; } = new HashSet<ImageLink>();
    ...
}

public class A : X {
    ...
}

public class B : X {
    ...
}

public class <MANY OTHER CLASSES> : X {
    ...
}


public class ImageLink {
    public int EntityId { get; protected set; }
    public int ImageId { get; protected set; }
    public virtual X Entity { get; protected set; }
    public virtual Image Image { get; protected set; }
    public int Position { get; private set; }
    ....
}

I would like my ef core model to have this kind of inheritance because I don't want to repeat some partial views/controllers code and because it makes sense to me. I know I can't do this because the image link entity will be mapped in a single table but I need a table for each many-to-many relationship.

Any ideas?

1 Answers

You can configure a different image table per entity if you use owned entities

Now, I couldn't get the navigation property to work from ImageLink to X, but it might be possible to do with generics or something.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<A>().OwnsMany(a => a.ImageLinks, e =>
    {
        e.ToTable("ImageLinksForA");
        e.WithOwner();
    });

    modelBuilder.Entity<B>().OwnsMany(a => a.ImageLinks, e =>
    {
        // Letting EF pick a table name for me
        e.WithOwner();
    });
    
    // Repeat for each descendent of X
}
Related