多个级联路径错误实体框架代码优先

时间:2012-01-18 09:58:40

标签: c# entity-framework ef-code-first

我知道这已经在很多场合提出过了 没有提供的答案似乎有帮助。我知道 基本问题并使用流畅的api尝试修改它 行为,但它似乎被忽略(或我做错了'。 这是一个例子 有问题的代码

public class Request
{
    [Key]
    public int RequestID { get; set; }
    public string RequestDescription { get; set; }
    public int RequestPriority { get; set; }
    public string RequestStub { get; set; }
    [ForeignKey("Requester")]
    public int RequesterID { get; set; }
    [ForeignKey("Admin")]
    public int AdminID { get; set; }
    public bool RequestAnsweredFlag { get; set; }
    public bool RequestSeenFlag { get; set; }


    public virtual User Requester {get;set;}
    public virtual User Admin { get; set; }

}

上下文类

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {


        modelBuilder.Entity<Request>()
                .HasRequired(a => a.Requester)
                .WithMany()
                .HasForeignKey(u => u.RequesterID);

        modelBuilder.Entity<Request>().HasRequired(a => a.Admin)
                       .WithMany()
                       .HasForeignKey(u => u.AdminID).WillCascadeOnDelete(false);

    }

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

如果我理解所有正确的你需要删除属性[ForeignKey(“Requester”)],[ForeignKey(“Admin”)]并删除流畅的api规则。并修改您的代码,如下所示

public class Request
{
    [Key]
    public int RequestID { get; set; }
    public string RequestDescription { get; set; }
    public int RequestPriority { get; set; }
    public string RequestStub { get; set; }
    public int RequesterID { get {return Requester.Id} }
    public int AdminID { get {return Admin.Id} }
    public bool RequestAnsweredFlag { get; set; }
    public bool RequestSeenFlag { get; set; }

    public virtual User Requester {get;set;}
    public virtual User Admin { get; set; }

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}

默认情况下它应该正确映射