Ste*_*ven 3 entity-framework fluent entity-framework-4.1
如何为这种类型设置流畅的映射?
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; }
}
Run Code Online (Sandbox Code Playgroud)
我假设不需要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; }
}
Run Code Online (Sandbox Code Playgroud)
然后映射看起来类似于
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
}
}
Run Code Online (Sandbox Code Playgroud)
和模型绑定插件:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TopicMap());
//modelBuilder.Configurations.Add(new TopicChildrenMap()); ..etc
//modelBuilder.Configurations.Add(new TopicRelatedMap()); ..etc
}
Run Code Online (Sandbox Code Playgroud)
我还建议您开始使用EF Power Tools CTP.这对学习和理解如何创建流畅的配置非常有帮助.
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
2580 次 |
| 最近记录: |