我希望能够输入SupplyPoint.SupplyPointMeters
,而后者则是一个集合。 Code First已经创建了表并正确设置了外键,但我希望能够以这种方式访问SupplyPoint.SupplyPointMeters
。
因此,在摘要SupplyPointMeter
中,始终有SupplyPoint
但SupplyPoint
可以有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; }
}
答案 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; }
}
这会生成以下表格