5

如果我有一个导航属性(即:虚拟),例如:
public virtual User Author { get; set; }

而且我还想拥有该用户的ID,即:
public int AuthorId { get; set; }

我如何告诉 EF 这个“AuthorId”必须与 Author 属性相关?

我不喜欢这种自动的想法(EF神奇地推断出这一点)。
因为一个人可能对同一张表有多个引用:

public virtual User Author { get; set; }
public int AuthorId { get; set; }
public virtual User Receiver { get; set; }
public int ReceiverId { get; set; }
4

1 回答 1

8

实体框架将假定 AuthorID 是 Author 类的 FK。有关详细信息,请参阅此博客文章

您还可以通过使用数据注释明确告诉 EF:

[ForeignKey("Author")]
public int AuthorId {get;set;}

或通过使用流畅的映射:

modelBuilder.Entity<YourClass>().HasRequired(p => p.Author)
                .WithMany()
                .HasForeignKey(p => p.AuthorId);
于 2012-09-04T20:43:16.517 回答