Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent API - one to many

I cannot seem to find a one-to-many relationship syntax in the fluent API.

As an example I have two tables as below

User

Id
Name

UserHistory

Id
UserId
Date

In the classes I have the following

public class User 
{
     public int Id { get; set; }
     public virtual ICollection<UserHistory> Histories { get; set; }
}

public class UserHistory
{
     public int Id { get; set; }
     public int UserId { get; set; }
     public DateTime Date { get; set; }
}

I have tried the following but I am not sure if its actually correct.

modelBuilder.Entity<User>()
       .HasRequired(w => w.Histories)
       .WithMany();

modelBuilder.Entity<User>()
       .HasMany(f => f.Histories)
       .WithOptional()
       .HasForeignKey(f => f.UserId);

What is the correct syntax for one-to-many relationship?

Technically I could break it down to a many-to-many by adding a new table but I didn't want to introduce another table.

like image 617
fes Avatar asked Jan 12 '13 17:01

fes


1 Answers

In your model a User entity has many Histories with each history having a required User and the relationship has a foreign key called UserId:

modelBuilder.Entity<User>()
   .HasMany(u => u.Histories)
   .WithRequired()
   .HasForeignKey(h => h.UserId);

(The relationship must be required (not optional) because the foreign key property UserId is not nullable.)

like image 130
Slauma Avatar answered Oct 17 '22 22:10

Slauma