在 c# 中为 C# 中的递归嵌套对象创建 EF 映射器配置
本文关键字:创建 对象 EF 映射 配置 嵌套 递归 中为 | 更新日期: 2023-09-27 18:31:38
我正在使用Visual Studio 2010。净4.
我在尝试使用 EF 将映射器配置到数据库时遇到问题。
这是我尝试映射的类,我正在尝试映射它,以便我可以使用 include 语句根据列表中问题对象的 ParentID 属性填充子项列表。
public class Question
{
public int QuestionId { get; set; }
public int ParentId { get; set; }
public string QuestionText { get; set; }
public string Answer { get; set; }
//recursive list of Questions
public virtual List<Question> Children {get; set;}
}
这是我配置映射器的尝试
class QuestionConfiguration : EntityTypeConfiguration<Question>
{
public QuestionConfiguration()
: base()
{
this.HasKey(x => x.QuestionId);
this.Property(p => p.ParentId)
.HasColumnName("ParentId");
this.Property(p => p.QuestionText)
.HasColumnName("QuestionText");
this.Property(p => p.Answer)
.HasColumnName("Answer");
this.HasMany(w => w.Children)
.HasForeignKey(w => w.ParentId);
ToTable("tbl_Questions");
}
}
我对 EF 和 c# 仍然相当陌生,所以我不确定如何从这里开始。我上面的尝试甚至没有编译。
任何正确方向的帮助或指示都将是一个很大的帮助。
你很接近:
this.HasMany(w => w.Children)
.WithOptional() // Added this
.HasForeignKey(w => w.ParentId);
唯一的问题是,我认为 ParentId 应该是一个可为空的int
,因为层次结构的根永远不会有父级。