2

I'm using Entity Framework Code First approach. I have these to classes. Of course, they have other fields but, they are not connected with the issue.

public class User
{
    public int Id { get; set; }
    public Role Role { get; set; }
    public int HouseholdId { get; set; }

    public virtual Household Household { get; set; }
}

public class Household
{
    private ICollection<User> users;

    public Household()
    {
        users = new HashSet<User>();
    }

    public int Id { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

I have the following settings applied in my OnModelCreating method:

modelBuilder.Entity<User>()
            .HasRequired(u => u.Household)
            .WithMany()
            .WillCascadeOnDelete(false);

When I run the application, everything is correct except of the fact that the generated User table has one more foreign key added to its design:

User Table:

Id
Role
HouseholdId
**Household_Id**

Why is this happening?

Yulian
  • 6,262
  • 10
  • 65
  • 92
  • I think that this answers your question: http://stackoverflow.com/questions/10909061/why-am-i-getting-an-extra-foreign-key-column-with-entity-framework-code-first-fo?rq=1 – Mark Verkiel Oct 29 '15 at 08:13
  • Thanks, but actually it doesn't. I haven't got two properties referring to the same class / entity. – Yulian Oct 29 '15 at 09:20

1 Answers1

1

Just remove this from your code:

modelBuilder.Entity<User>()
        .HasRequired(u => u.Household)
        .WithMany()
        .WillCascadeOnDelete(false);

EDIT: If you need WillCascadeOnDelete(false) and cannot remove this code try this:

modelBuilder.Entity<User>()
        .HasRequired(u => u.Household)
        .WithMany(t => t.Users)
        .WillCascadeOnDelete(false);
Aleksa
  • 2,976
  • 4
  • 30
  • 49
  • I've put it there for a reason. If I remove it from my code I get an exception: Unhandled Exception: System.Data.SqlClient.SqlException: Introducing FOREIGN KEY constraint 'FK_dbo.User_dbo.Household_HouseholdId' on table 'User' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. – Yulian Oct 29 '15 at 09:21
  • Ahh, yes, it's working now, thank you :)) I've spent more than 3 hrs digging into this. – Yulian Oct 29 '15 at 09:37