Infolord101
Infolord101

Reputation: 45

Multiple cascade paths error entity framework Code first

I am aware that this has been raised on numerous occasions but none of the provided answers seem to help.I am aware of the basic problem and have used fluent api to try to modify it's behaviour but it appears this is being ignored(or i'm doing it wrong'. Here's a example of the code in question

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

}

context class

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

    }

any help would be much appreciated.

Upvotes: 0

Views: 460

Answers (1)

Ph0en1x
Ph0en1x

Reputation: 10067

If I understand all correct you need to delete attributes [ForeignKey("Requester")], [ForeignKey("Admin")] and delete fluent api rules. And modify your code as follow

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)
{
}

it should map all correctly by default

Upvotes: 1

Related Questions