Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 Code First Foreign Key adds Extra column

I have the following two entities (among many, but these give me the problem)

public class StartPoint
{
    public int StartPointId { get; set; }
    public string Description { get; set; }
    public int StartPointNumber { get; set; }    
    public int StartAreaId { get; set; }
    public StartArea StartArea { get; set; }
}    

and

public class StartArea
{
    public int StartAreaId { get; set; }
    public string Description { get; set; }
    public ICollection<StartPoint> StartPoints { get; set; }
}

When allowing EF to create my database it complained that I needed to turn off cascade delete because of multiple paths, which I have done as follows.

        modelBuilder.Entity<StartPoint>()
            .HasRequired(x => x.StartArea)
            .WithMany()
            .HasForeignKey(x => x.StartAreaId)
            .WillCascadeOnDelete(false);

The problem is, when the database is created I get two foreign keys, one is called StartAreaId, as I would expect, and the other is StartArea_StartAreaId. Only StartAreaId is being used. Why and how do I get rid of the StartArea_StartAreaId. If I remove the HasForeignKey in the context and remove the StartAreaId from the entity I get multiple StartArea_StartAreaId columns, as in StartArea_StartAreaId and StartArea_StartAreaId1. What do I need to do to stop this from happening ? I just want StartAreaId as my foreign key.

like image 620
Dirk Avatar asked Oct 25 '22 07:10

Dirk


1 Answers

The problem is empty WithMany:

    modelBuilder.Entity<StartPoint>()
        .HasRequired(x => x.StartArea)
        .WithMany(y => y.StartPoints)
        .HasForeignKey(x => x.StartAreaId)
        .WillCascadeOnDelete(false);
like image 146
Ladislav Mrnka Avatar answered Oct 30 '22 22:10

Ladislav Mrnka