Fluent API - one to many

醉酒当歌 提交于 2019-11-29 12:03:48

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/14295705/fluent-api-one-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!