ctorx
ctorx

Reputation: 6941

Database First with Bridge Table, How to Keep It Out of Model

I am trying to find out how I can make a bridge table entity, used for a many to many relationship, transparent to my model. I am using EF Database First.

Tables in question...(simplified)

Report
- ReportId INT PK
- ReportName VARCHAR(50)

Group
- GroupId INT PK
- GroupName VARCHAR(50)

ReportGroup
 - ReportId INT PK
 - GroupId INT PK

Current Class Structure...(simplified)

public class Report
{
     public int ReportId { get; set; }
     public string ReportName { get; set; }
     public IList<ReportGroup> ReportGroups { get; set; }
}

public class Group
{
     public int GroupId { get; set; }
     public string GroupName { get; set; }
     public IList<ReportGroup> ReportGroups { get; set; }
}

public class ReportGroup
{
     public int ReportId { get; set; }
     public Report Report { get; set; }
     public int GroupId { get; set; }
     public Group Group { get; set; }
}

Using the above, to get the groups that a Report belongs to requires something like this...

// Getting a report's groups
var report = this.ReportService.GetReportById(123456);
var groups = report.ReportGroups.Select(x => x.Group).ToList();

That's not exactly something I want to be using throughout my application. Ideally, I'd like the bridge table and Entity (ReportGroup) to be transparent, allowing me to work with the entities like this...

// Getting a report's groups
var report = this.ReportService.GetReportById(123456);
var groups = report.Groups;

// Getting a group's reports
var group = this.ReportService.GetGroupById(1);
var reports = group.Reports;

So my question is whether this is possible with EF Database First, and if so, how do I wire this up correctly using the Fluent API in OnModelCreating().

Thanks in advance for the help.

Upvotes: 3

Views: 1633

Answers (1)

Denis Agarev
Denis Agarev

Reputation: 1529

You if use ReportGroup just for relations you don't need this POCO class just map it OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Configurations.Add(new GroupMap());
...
}

public class GroupMap : EntityTypeConfiguration<Group>
    {
        public GroupMap()
        {
            // Relationships
            this.HasMany(e => e.Reports)
              .WithMany(set => set.Groups)
              .Map(mc =>
              {
                  mc.ToTable("groupreporttablename");
                  mc.MapLeftKey("GroupID");
                  mc.MapRightKey("ReportID");
              });
        }
    }

Upvotes: 3

Related Questions