简体   繁体   中英

Same table for two many to many relationships with Entity Framework

I'm trying create two many to many relationships in Entity Framework using the same intermediate table.

Is possible use the same table for two relationship using Entity Framework?

public class Alert
{
    public Alert()
    {
        Users = new HashSet<SXUser>();
        Groups = new HashSet<Group>();
    }

    public Guid AlertId { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }

    public virtual ICollection<SXUser> Users { get; set; }
    public virtual ICollection<Group> Groups { get; set; }
}

public class SXUser
{
    public Guid UserId { get; set; }
    public string Name { get; set; }
}

public class Group
{
    public int GroupId { get; set; }
    public string Description { get; set; }
}

In database I have:

数据库

How configure the relationship in mapping? I tried:

public class AlertMap : EntityTypeConfiguration<Alert>
{
    public AlertMap()
    {
        // Primary Key
        HasKey(t => t.AlertId);

        // Properties
        Property(t => t.AlertId).IsRequired()
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(t => t.Code).IsRequired()
            .HasColumnAnnotation(
                IndexAnnotation.AnnotationName,
                new IndexAnnotation(new IndexAttribute("AK_Alert", 1) { IsUnique = true })
            );

        Property(t => t.Name).IsRequired();


        // Relationships
        HasMany(t => t.Users).WithMany().Map(t=>t.ToTable("AlertRecipient").MapLeftKey("AlertId").MapRightKey("UserId"));
        HasMany(t => t.Groups).WithMany().Map(t => t.ToTable("AlertRecipient").MapLeftKey("AlertId").MapRightKey("GroupId"));
    }
}

It is possible?

If you use a middle table you can only define an ICollection of that middle table in every Alert/User. So for example User:

virtual ICollection<AlertRecipient> {get; set;}

for Alertrecipient:

virtual Alert {get; set;}
virtual User {get; set;}

Also add the ID's of Alert and User in your Alertrecipient model. In fluent API your mapping for Alertrecipient will look something like this:

ModelBuilder<AlertRecipient>().HasRequired(e => e.User)
.WithMany(e => e.AlertRecipient).HasForeignKey(e => e.UserIDInMiddleTable);

I've never done two many-to-many relations with one table, but I imagine with this technique it should be possible.

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