流利的API-一对多 [英] Fluent API - one to many
问题描述
我似乎无法在流畅的API中找到一对多的关系语法。
I cannot seem to find a one-to-many relationship syntax in the fluent API.
例如,我有两个如下表
用户
Id
Name
UserHistory
Id
UserId
Date
我有以下课程
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.
推荐答案
在您的模型中, User
实体有很多 历史记录
,每个历史记录都有一个必需 用户
,并且关系为具有一个名为 UserId
的外键:
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);
(该关系必须是必需的(非可选),因为外键属性 UserId
不能为空。)
(The relationship must be required (not optional) because the foreign key property UserId
is not nullable.)
这篇关于流利的API-一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!