EF6 Code First不映射我的M-0关系

时间:2013-12-06 12:08:21

标签: c# entity-framework

我希望能够输入SupplyPoint.SupplyPointMeters,而后者则是一个集合。 Code First已经创建了表并正确设置了外键,但我希望能够以这种方式访问​​SupplyPoint.SupplyPointMeters

因此,在摘要SupplyPointMeter中,始终有SupplyPointSupplyPoint可以有0或更多SupplyPoint米。一切正常但我希望关系自动加入以支持点符号。

public partial class SupplyPointMeter
{
    [Key]
    public int SupplyPointMeterId { get; set; }
    public int SupplyPointId { get; set; }

    [Key,ForeignKey("SupplyPointId")]
    public virtual SupplyPoint SupplyPoint { get; set; }
}

public partial class SupplyPoint
{
    [Key]
    public int SupplyPointId { get; set; }

    public virtual ICollection<SupplyPointMeter> SupplyPointMeters { get; set; }
}

2 个答案:

答案 0 :(得分:0)

以这种方式试试。

public class SupplyPointMeter
{
    public int Id { get; set; }
    public virtual SupplyPoint SupplyPoint { get; set; }
}

public class SupplyPoint
{
    public int Id { get; set; }
    public virtual ICollection<SupplyPointMeter> SupplyPointMeters { get; set; }
}

答案 1 :(得分:0)

我建议您使用fluent mapping

modelBuilder.Entity<SupplyPoint>()
    .HasMany(sp => sp.SupplyPointMeters)
    .WithRequired(spm => spm.SupplyPoint)
    .HasForeignKey(spm => spm.SupplyPointId);

此外,您不需要标记密钥 - 如果密钥属性与type_name + id模式匹配,那么按惯例它将被视为关键:

public partial class SupplyPointMeter
{        
    public int SupplyPointMeterId { get; set; }
    public int SupplyPointId { get; set; }
    public virtual SupplyPoint SupplyPoint { get; set; }
}

public partial class SupplyPoint
{
    public int SupplyPointId { get; set; }
    public virtual ICollection<SupplyPointMeter> SupplyPointMeters { get; set; }
}

这会生成以下表格

enter image description here