3

因此,我将使用带有帖子和评论的博客数据库模型的陈词滥调示例。

public class Post {
  public int Id { get; set; }
  public string Title { get; set; }
  public string Body { get; set; }
  public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment {
  public int Id { get; set; }
  public string Body { get; set; }
  public virtual Post Post { get; set; }
}

当然,Post与 有一对多的关系Comment

如果我让 Entity Framework 为我创建数据库,它会在表中添加一Post_IdComments。我想改为命名列PostId,但我不想PostId向我的Comments类添加属性。有没有办法通过DataAnnotationsDbModelBuildermigrations,我不知道的其他东西来实现这一点?

如果这个问题已经得到解答,我深表歉意,但我无法在 SO 甚至谷歌上找到它。谢谢。

4

2 回答 2

4

在我发布这个之后,我找到了答案。

在派生自 DbContext 的类上声明此方法。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Comment>()
    .HasRequired(t => t.Post)
    .WithMany(t => t.Comments)
    .Map(m => m.MapKey("PostId"));
}
于 2012-08-21T05:55:13.027 回答
1

你也可以用注解来做到这一点:

public class Comment {
  public int Id { get; set; }
  public string Body { get; set; }

  public virtual Post Post { get; set; }
  [ForeignKey("Post")]
  public int PostId { get; set; }
}

接受一个参数,即该ForeignKeyAttribute列作为外键的导航属性的名称。

于 2015-07-07T18:39:41.770 回答