简体   繁体   中英

Mutiple entities in a many to many relationship in Entity Framework

Lets say i have 3 classes:

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

public class Post {
     public virtual IList<Tag> Tags { get; set; }
}

public class User {
     public virtual IList<Tag> Tags { get; set; }
}

Now, there's a many to many relations between both users and tags, and also posts and tags.

Simplified: I have a list of tags, i want to be able to tag both users and posts, while the tags remain independent.

Now, i could just create a map and map a double many to many, creating two tables: Users_Tags and Posts_Tags, but I need them to be in the same table.

I need a: Entities_Tags: Entity_Id, Tag_Id, Descriminator

Usually i would make a base class, that both Tag and Post inherit from... "TagContainer". Creating a: TagContainers_Tags: TagContainer_Id, Tag_Id

The problem now is that in my situation, in the entities i have in mind it doesn't make sense that they share the same base class. This is because i have another base class doing the same thing that will conflict. And having that class inherit one of these base classes wouldn't make sense application wise.

Had EF had support for interfaces i would of course solved this by having my classes inheriting the necessary interfaces to support both the first and the second many-to-many entity.

I'm pretty much looking for a way to have EF support Discriminator based many-to-many tables without having to supply base classes to my entities.

Any suggestions?

So, you cannot use the table in two different many-to-many relationships. if you really don't want to make any kind of generalization in both model and database tables(although it's most common in normalizing big database design) you can act like this:

public class MyTrust
    {
        public MyTrust()
        {
            MyLocations = new List<MyLocation>();
        }
        public int MyTrustID { get; set; }
        public string MyTrustName { get; set; }
        public virtual ICollection<MyLocation> MyLocations { get; set; }
    }
    public class MyLocation
    {

        public int MyLocationID { get; set; }
        public string MyLocationName { get; set; }
        public virtual MyTrust MyTrust { get; set; }
}

public class TaskDbContext : DbContext
    {
        public DbSet<MyTrust> MyTrusts { get; set; }
        public DbSet<MyLocation> MyLocations { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MyTrust>().HasMany(t => t.MyLocations).WithRequired();
        }
    }

see the source of the sample here

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