user557419
user557419

Reputation:

EF6 Code First confusion when having 2 properties using the same entity

I'm creating my database using the Code First approach which is working perfectly so far. However I have a minor issue which EF6 somehow can't seem to fathom or I'm doing it wrong.

I have class Project which has a property CreatedBy of type Person and another property Members of type ICollection<Person>;

public class Project
{
    // ...
    public Person CreatedBy { get; set; }
    public virtual ICollection<Person> Members { get; set; }
}

In class Person I have added the following property:

public virtual ICollection<Project> Projects { get; set; }

To tell EF6 that there is supposed to be a Many-to-Many relationship between the 2 classes.

If I run a Add-Migrationand Update-Database in Visual Studio with CreatedBy commented out in the Project class, what will happen is that a Project <-> Person table will be created in the database.

If I then uncomment the CreatedBy property and run the same scripts again the Project <-> Person table gets deleted and both Project and Person tables get a new column with a ForeignKey between the two changing it to a 1-to-1 relationship.

How can I, using Code First, set up a relationship between my Project and Person class so I can how both a 1-to-Many (1 person can create many projects) and a Many-to-Many (many persons can be added to many projects)?

Upvotes: 0

Views: 232

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

I haven't verified this, but if you specify and explicit foreign key for your Created by, it should be enough to differentiate the two different relationships:

// make nullable if CreatedBy is not required
[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public Person CreatedBy { get; set; }

Upvotes: 0

sribin
sribin

Reputation: 1736

You need to use Fluent API for configuration entity:

    class ProjectConfiguration : EntityTypeConfiguration<Project>
    {
        public ProjectConfiguration()
        {
            HasRequired(e => e.CreatedBy).WithMany(); // one-to-many
            HasMany(e => e.Members).WithMany(); //many-to-many
        }
    }

    public class Context : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ProjectConfiguration());
        }
    }

More detail about the Fluent API: http://msdn.microsoft.com/en-us/data/jj591617.aspx

Configuring Relationships with the Fluent API: http://msdn.microsoft.com/en-us/data/jj591620

Upvotes: 3

Related Questions