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

你说的曾经没有我的故事 提交于 2019-12-24 02:12:34

问题


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.


回答1:


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");
              });
        }
    }


来源:https://stackoverflow.com/questions/9745057/database-first-with-bridge-table-how-to-keep-it-out-of-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!