EF6外键定义

问题描述:

要定义外键,因为我知道,我只引用了场就像this text解释说:EF6外键定义

public class Book 
{ 
    public int Id { get; set; } 
    [Required] 
    public string Title { get; set; } 
    public int Year { get; set; } 
    public decimal Price { get; set; } 
    public string Genre { get; set; } 

    // Foreign Key 
    public int AuthorId { get; set; } 
    // Navigation property 
    public Author Author { get; set; } 
} 

但对我来说这种方法是行不通的,我需要使用这样的代码:

[ForeignKey("MyFkName")] 
public virtual ForeignKeyTable ForeignKeyProperty { get; set; } 
public int? MyFkName{ get; set; } 

我在做什么错了?

+1

*什么*不起作用?你的代码没有什么明显的错误。 –

+0

你添加了作者类并给它一个ID吗? –

+0

嗨,如果我只使用:public int MyFkProperty {get;组; }创建fk,表格只是用INT列创建而不是外键 – GCoe

错误在于您忘记声明您的作者属性虚拟;

// a Book belongs to exactly one Author using Foreign Key: 
public int AuthorId {get; set;} 
pubic virtual Author Author {get; set;} 

而且您的作者应该有它的书籍参考:

// Every Author has zero or more Books: 
public ICollection<Book> Books {get; set;} 

这是所有需要告知对方您正在建模一个一对多的关系

实体框架

你的Author属性应该声明为虚拟是有道理的。毕竟,您的图书没有将作者数据作为数据随时提供。

当寻址Book.Author中的某个属性时,实体框架必须创建连接查询而不是返回数据。

因此,在作者属性的Author是不是一个真正的Author,但是从Author派生的对象,它知道如何从数据库中获取的BookAuthor数据。

+0

好吧,如果我使用公共虚拟作者Author {get;设置;} fk创建好。但在https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-2上,据我所知,作者说导航属性(公共虚拟作者作者{get; set;})是可选的... – GCoe

+0

我试过它没有虚拟,它没有工作。正如我写的,虚拟是有道理的。有时你只需填写Book.Author = new Author(){...},这意味着作者只是一些数据。但是,如果您执行DbSet查询并使用Book.Author,则这是内部Linq加入操作。这不能没有虚拟的工作 –