Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple one to many relationships with Entity Framework

I am using EntityFramework 4.1.

I have the following model:

public class User 
{
   [Key]
   public int Id { get; set; }
   public string Username { get; set; } 
   public string Password { get; set; }

   public virtual User Creator { get; set; }
   public virtual User LastEditor { get; set; }
}

When I try to generate my database I got this error:

Unable to determine the principal end of an association between the types 'User' and 'User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

But I also have this class:

public class Course 
{
   [Key]
   public int Id { get; set; }
   public string Name { get; set; } 

   public virtual User Creator { get; set; }
   public virtual User LastEditor { get; set; }
}

And it works ok, I have these foreign keys generated:

Creator_Id
LastEditor_Id

Do I have anything to add in my User model to make it works?

like image 726
Charles Ouellet Avatar asked Jun 14 '12 15:06

Charles Ouellet


People also ask

How do I remove a one to many relationship in Entity Framework?

after manual set the property,single call to "dbContext. As. Remove(someA)" work as expected!

How will you create relationship between tables in Entity Framework?

You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.

What is OnModelCreating in Entity Framework?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.


1 Answers

EF tries - by convention - to create a one-to-one relationship between User.Creator and User.LastEditor because they both refer to the User class where they are themselves located in. That's not the case for the Course class. For Course.Creator and Course.LastEditor EF creates two one-to-many relationships to the User. To achieve the same for the properties in User you will have to configure the relationships with Fluent API:

modelBuilder.Entity<User>()
    .HasOptional(u => u.Creator)     // or HasRequired
    .WithMany();

modelBuilder.Entity<User>()
    .HasOptional(u => u.LastEditor)  // or HasRequired
    .WithMany();
like image 191
Slauma Avatar answered Nov 09 '22 12:11

Slauma