gpt4 book ai didi

entity-framework - 为 Entity Framework 4.1 设置递归映射

转载 作者:行者123 更新时间:2023-12-04 08:32:26 26 4
gpt4 key购买 nike

如何为这种类型设置流利的映射?

public class Topic
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Topic> Children { get; set; }
public int ParentId { get; set; }
public Topic Parent { get; set; }
public virtual ICollection<Topic> Related { get; set; }
}

最佳答案

我假设 ParentId 不是必需的,因为并非每个主题都有父主题。

public class Topic
{
public int Id { get; set; }
public string Title { get; set; }
public int? ParentId { get; set; }
public Topic Parent { get; set; }
public virtual ICollection<Topic> Children { get; set; }
public virtual ICollection<Topic> Related { get; set; }
}

那么映射看起来类似于

public class TopicMap : EntityTypeConfiguration<Topic>
{
public TopicMap()
{
HasKey(t => t.Id);

Property(t => t.Title)
.IsRequired()
.HasMaxLength(42);

ToTable("Topic");
Property(t => t.Id).HasColumnName("Id");
Property(t => t.Title).HasColumnName("Title");
Property(t => t.ParentId).HasColumnName("ParentId");

// Relationships
HasOptional(t => t.Parent)
.WithMany()
.HasForeignKey(d => d.ParentId);
//Topic might have a parent, where if it does, has a foreign key
//relationship to ParentId
}
}

模型绑定(bind)插件:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TopicMap());
//modelBuilder.Configurations.Add(new TopicChildrenMap()); ..etc
//modelBuilder.Configurations.Add(new TopicRelatedMap()); ..etc
}

我还建议您亲自动手 the EF Power Tools CTP .这对学习和理解如何创建流畅的配置非常有帮助。

希望对您有所帮助。

关于entity-framework - 为 Entity Framework 4.1 设置递归映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6482542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com