3

多対多の関係に使用される、モデルに対して透過的なブリッジテーブルエンティティを作成する方法を見つけようとしています。私はEFデータベースファーストを使用しています。

問題のテーブル...(簡略化)

Report
- ReportId INT PK
- ReportName VARCHAR(50)

Group
- GroupId INT PK
- GroupName VARCHAR(50)

ReportGroup
 - ReportId INT PK
 - GroupId INT PK

現在のクラス構造...(簡略化)

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

上記を使用して、レポートが属するグループを取得するには、次のようなものが必要です...

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

これは、アプリケーション全体で使用したいものではありません。理想的には、ブリッジテーブルとエンティティ(ReportGroup)を透過的にして、このようなエンティティを操作できるようにします...

// 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;

だから私の質問は、これがEF Database Firstで可能かどうかです。可能であれば、 OnModelCreating() のFluentAPIを使用してこれを正しく接続するにはどうすればよいですか。

助けてくれてありがとう。

4

1 に答える 1

3

リレーションのためだけにReportGroupを使用する場合は、このPOCOクラスは必要ありません。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");
              });
        }
    }
于 2012-03-16T22:19:47.790 に答える