【问题标题】:Mapping relationships that require a navigation property only on one side仅在一侧需要导航属性的映射关系
【发布时间】:2015-07-01 14:20:20
【问题描述】:

我有这个模型:

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(???);
    }
}

如何映射?

【问题讨论】:

    标签: entity-framework entity-framework-6


    【解决方案1】:

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

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

    顺便说一句,即使你不配置 EF 也可能能够推断出这种关系,但显式配置它就很好了。

    【讨论】:

    • 这是我想出的一些例子,不是真正的模型。在这个模型中,我真的不关心博客除了标题之外还有什么,我不希望 Blog 实体上的每个引用它的实体都有导航属性。在我的模型上,根据您的建议,我得到了类似 Invalid column name 'Blog_ID' 之类的信息。
    • 它实际上是在做正确的连接,但没有明显的原因选择Post.Blog_ID
    • @PauloMorgado: 嗯,Property(t =&gt; t.BlogID).HasColumnName("BlogID"); 应该解决这个问题...
    • 生成的查询类似于:SELECT [Extent1].[ID], [Extent1].[Title], [Extent1].[Content], [Extent1].[BlogID], [Extent2].[ID], [Extent2].[Title], [Extent1].[Blog_ID] FROM [dbo].[Posts] AS [Extent1] INNER JOIN [dbo].[Blogs] as [Extent2] ON [Extent1].[BlogID] = [Extent2].[ID]
    • @PauloMorgado:Property(t =&gt; t.BlogID) 有其他配置吗?如果您将Property(t =&gt; t.BlogID).HasColumnName("BlogID"); 放在关系配置之后,它会起作用吗(这更像是一个疯狂的猜测)?
    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    相关资源
    最近更新 更多