映射实体框架中的奇数关系6

时间:2015-04-23 17:32:18

标签: entity-framework entity-framework-6 relationships

我有一组3个模型,这是一个奇怪的多对多关系。

public class Metric {
    public int Id { get; set; }
    public string Name { get; set; }
    // ...
}

public class ActionPlan {
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    //...

    public virtual ICollection<Metric> Metrics { get; set; }
}

public class PlanMetric {
    public int PlanId { get; set; }
    public int MetricId { get; set; }
    public decimal GoalValue { get; set; }

    public virtual ActionPlan Plan { get; set; }
    public virtual Metric Metric { get; set; }
}

我的关系映射如下:

public class PlanMetricMapping : EntityTypeConfiguration<PlanMetric> {
    public PlanMetricMapping() {
        ToTable("PlanMetric");

        HasKey(m => new {
            m.MetricId,
            m.PlanId
        });

        Property(m => m.GoalValue)
            .IsRequired()
            .HasPrecision(10, 2);

        HasRequired(m => m.Metric)
            .WithMany()
            .HasForeignKey(m => m.MetricId);

        HasRequired(m => m.Plan)
            .WithMany()
            .HasForeignKey(m => m.PlanId);
    }
}

public class ActionPlanMapping : EntityTypeConfiguration<ActionPlan> {
    public ActionPlanMapping() {
        ToTable("ActionPlan");

        HasKey(m => m.Id);

        // ...

        //HasMany(m=>m.Metrics) // how do I get to this data?
    }
}

问题是

1)EF正在我的ActionPlan_Id表格中创建Metric字段,我不确定原因。

2)我不知道如何设置我的地图,以便能够从Plan导航到Metrics

1 个答案:

答案 0 :(得分:0)

EF正在创建ActionPlan_Id字段,因为您有

public virtual ICollection<Metric> Metrics { get; set; }

在您的ActionPlan定义中,EF将其解释为ActionPlanMetric之间的一对多关系。好像你想要

public virtual ICollection<PlanMetric> PlanMetrics { get; set; }

代替。

然后,为了获得ActionPlan指标,您可以通过Select()来浏览该集合。

相关问题