pnewhook
pnewhook

Reputation: 4068

Database Generated by EF5 Not Creating Join Table When There are Multiple Relationships

I have a User and an Organization class. They look like this

public class User
{
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual ICollection<Organization> Organizations { get; set; }
}

public class Organization : EntityBase
{
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

And both inherit from an EntityBase class to get common fields like Id and created/updated tracking.

public abstract class EntityBase
{
    public int Id { get; set; }
    public DateTime Created { get; set; }
    public virtual User CreatedBy { get; set; }
    public DateTime Updated { get; set; }
    public virtual User UpdatedBy { get; set; }
}

As denoted by the ICollection properties on both, there should be a many-to-many relation. However when my database is autogenerated I get incorrect foreign keys added to my tables Incorrect mapping of Organization and User tables

If I change the CreatedBy and UpdatedBy to be strings instead of User properties I get a join table, which is what I was looking for. Correct database generation

Is this a matter of Entity Framework simply being confused and I need to supply many-to-many configuration in the using fluent mappings, or have I done something wrong?

Upvotes: 1

Views: 460

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

If you have multiple relationships you need to configure them manually by fluent API or using attributes,

Note:If you have multiple relationships between the same types (for example, suppose you define the Person and Book classes, where the Person class contains the ReviewedBooks and AuthoredBooks navigation properties and the Book class contains the Author and Reviewer navigation properties) you need to manually configure the relationships by using Data Annotations or the fluent API

Here is the article from Microsoft.

Upvotes: 1

Related Questions