重构重复的EntityFramework的Fluent API语句

时间:2018-07-12 15:30:57

标签: c# .net entity-framework generics .net-core

我目前有以下(摘录)代码可以正确映射EF Core中的多对多关系:

<body style="text-align:center;">

  <p>Move the mouse over the text below:</p>

  <div class="tooltip">Hover over me
    <span class="tooltiptext">Some fairly long tooltip text that should <br /> only display on two lines.</span>
  </div>
</body>

这会持续一段时间。这些看起来非常重复,看起来像可以重构为一系列方法调用的东西,例如

        modelBuilder.Entity<LifeCourseNameTranslation>()
            .HasKey(pc => new { pc.TranslationId, pc.LifeCourseId });

        modelBuilder.Entity<LifeCourseNameTranslation>()
            .HasOne(pc => pc.LifeCourse)
            .WithMany(p => p.LifeCourseNameTranslations)
            .HasForeignKey(pc => pc.LifeCourseId);

        modelBuilder.Entity<LifeCourseNameTranslation>()
            .HasOne(pc => pc.Translation)
            .WithMany(c => c.LifeCourseNameTranslations)
            .HasForeignKey(pc => pc.TranslationId);


        modelBuilder.Entity<StrataNameTranslation>()
            .HasKey(pc => new { pc.TranslationId, pc.StrataId });

        modelBuilder.Entity<StrataNameTranslation>()
            .HasOne(pc => pc.Strata)
            .WithMany(p => p.StrataNameTranslations)
            .HasForeignKey(pc => pc.StrataId);

        modelBuilder.Entity<StrataNameTranslation>()
            .HasOne(pc => pc.Translation)
            .WithMany(c => c.StrataNameTranslations)
            .HasForeignKey(pc => pc.TranslationId);


        modelBuilder.Entity<PointLabelTranslation>()
            .HasKey(pc => new { pc.TranslationId, pc.PointId });

        modelBuilder.Entity<PointLabelTranslation>()
            .HasOne(pc => pc.Point)
            .WithMany(p => p.PointLabelTranslations)
            .HasForeignKey(pc => pc.PointId);

        modelBuilder.Entity<PointLabelTranslation>()
            .HasOne(pc => pc.Translation)
            .WithMany(c => c.PointLabelTranslations)
            .HasForeignKey(pc => pc.TranslationId);

这可能吗?

0 个答案:

没有答案