13

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.

4

1 回答 1

27

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.)

于 2013-01-12T17:33:55.933 回答