简体   繁体   中英

Can't get EF code first one-to-many working

Picking up from post: Define one-to-one in EF code first with fluent API where I had trouble getting a one-to-one working, I now have another problem with a one-to-many.

Here are my two classes:

[Table("PSCStatuses")]
public class PSCStatus
{
    [Key]
    public int PSCStatusID { get; set; }
    public string StatusCode { get; set; }
    public string StatusTextDesc { get; set; }
    public int NumDaysToProjEndDate { get; set; }

    public virtual List<Case> Cases { get; set; }
}

public class Case
{
    // Key: Tells EF this is the PK for Case.
    // ForeignKey("Appointee"): tells EF Appointee is the Principle/Parent in the 1:1
    [Required]
    [Key, ForeignKey("Appointee")]  
    public string ProfileID { get; set; }

    [Required]
    public int? PSCStatusID { get; set; }

    public virtual PSCStatus PSCStatus { get; set; }
    public virtual Appointee Appointee { get; set; }
}

You can see here what I had to do in my previous post to get Case to have one Appointee. (And Appointee to have a Case where Appointee is the Principle/Parent). I don't recall ever having to jump through hoops with EF before. But I think I am very rusty here.

Now after solving that I have a new problem. I can't get Case to fill in PSCStatus. When I inspect Case.PSCStatus at a break point after adding the case with the PSCstatusID set, I should see the PSCStatus object filled in and populated. But it remains null. I would think that the definition above would tell EF everything it needs to know but it is not working.

I also tried fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Case>()
                    .HasRequired<PSCStatus>(c => c.PSCStatus)
                    .WithMany(s => s.Cases)
                    .HasForeignKey(c => c.PSCStatusID);
    }

Use: ICollection insead of List

[Edit]

If this doesn't work try this model builder:

modelBuilder.Entity<Case>()
        .HasRequired(c => c.PSCStatus)
        .WithMany(s => s.Cases)
        .HasForeignKey(c => c.PSCStatusID);

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