无法首先获得EF代码的一对多工作

时间:2015-02-11 16:02:17

标签: c# entity-framework

从帖子中挑选: Define one-to-one in EF code first with fluent API 如果我在一对一的工作中遇到麻烦,我现在又遇到了一对多的问题。

以下是我的两个课程:

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

你可以在这里看到我在上一篇文章中要做的事情让Case有一个被任命者。 (并且被任命为受理人是原则/父母的案例)。 我不记得曾经不得不用EF跳过篮球。但我觉得我在这里很生疏。

现在解决了我有一个新问题。 我无法让Case填写PSCStatus。 当我在添加具有PSCstatusID集的案例后在断点处检查Case.PSCStatus时,我应该看到填充并填充了PSCStatus对象。 但它仍然是空的。 我认为上面的定义会告诉EF它需要知道的一切,但它不起作用。

我也尝试过流畅的API:

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

1 个答案:

答案 0 :(得分:0)

使用: ICollection代替List

[编辑]

如果这不起作用,请尝试使用此模型构建器:

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