从数据库中获取对象的父ID(由MVC通过虚拟ICollection创建)

时间:2014-07-16 07:18:28

标签: c# asp.net-mvc linq entity-framework

我的数据库由EF-CodeFirst生成。我有3个型号,包含板,线程和帖子。我没有手动跟踪所有的parent_id值,而是使用一些ICollections创建它们,以便EF为我做这个。

然而,当我在Threads / View / 5页面上时,我希望能够获取其主板ID,但我不知道如何。该列确实存在于数据库中,因为所有EF都会创建一个Board_Id字段并在我创建线程并将其添加到数据库时填充它.Threads ICollection。

这是我的代码:

// Board model, containing a title and a collection of threads
public class Board
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Thread> Threads { get; set; }
}

// Thread model, containing a title and a collection of posts
public class Thread
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

现在,当我在线程/视图操作中时,如何从Board_Id列中获取值?

// GET: Threads/View/5
[AllowAnonymous]
public ActionResult View(int? id) {
    Thread thread = db.Threads.Find(id);

    // Fetch the parent board Id
    int boardId = ...;

    return View(thread);
}

1 个答案:

答案 0 :(得分:1)

你需要Thread类中的Board属性。该物业将

public virtual Board Board {get; set;}

使用该属性,您将能够从线程导航到主板