简体   繁体   中英

EF6 Code First not mapping my M-0 relationsip

I'm looking to be able to type SupplyPoint.SupplyPointMeters and for the latter to be a collection. Code First has created the tables and set the Foreign key correctly but I want to be able to access SupplyPoint.SupplyPointMeters that way.

So in Summary SupplyPointMeter always has a SupplyPoint but SupplyPoint can have 0 or more SupplyPoint Meters. Everything works but I want the relationships to join up automatically to support dot notation.

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

Try it this way.

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

I suggest you to use fluent mapping :

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

Also you don't need to mark keys - if key property matches type_name + id pattern, then it will be considered key by convention:

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

This generates following tables

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM