映射仅在一侧需要导航属性的关系

时间:2015-07-01 14:20:21

标签: entity-framework entity-framework-6

我有这个型号:

public class Blog
{
    public int ID { get; set; }
    public string Title { get; set; }
}

public class Post
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Content { get; set; } 
    public int BlogID { get; set; }
    public Blog Blog { get; set; }
}

具有以下配置:

public class BlogMap : EntityTypeConfiguration<Blog>
{
    public BlogMap()
    {
        this.ToTable("Blogs", "dbo");
        this.HasKey(t => t.ID);
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.Title).HasColumnName("Title");
    }
}

public class PostMap : EntityTypeConfiguration<Post>
{
    public PostMap()
    {
        this.ToTable("Posts", "dbo");
        this.HasKey(t => t.ID);
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.Title).HasColumnName("Title");
        this.Property(t => t.Content).HasColumnName("Content");
        this.Property(t => t.BlogID).HasColumnName("BlogID");
        this.HasRequired(t => t.Blog)
            .WithRequiredDependent()
            .Map(???);
    }
}

如何映射?

1 个答案:

答案 0 :(得分:5)

我猜测,如果像普通博客一样,每个博客都有很多帖子,那么你可能需要配置一对多的关系:

this.HasRequired(t => t.Blog)
    .WithMany() // no arguments means no inverse property
    .HasForeignKey(t => t.BlogID);

顺便说一下,即使您没有配置它,EF也可能能够推断出这种关系,但明确配置它是完全正常的。