EF代码首先4.3 - 如何将项目添加到列表<>?

时间:2012-08-12 18:08:08

标签: entity-framework list frameworks entity

我有这样的事情:

public class Category
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public List<Thread> Threads { get; set; }
}
public class Thread
{
    [Key]
    public int Id { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    [Key]
    public int Id { get; set; }
}

我不知道如何将线程项添加到现有类别。我试过这样的事情:

var context = new Db();
var thr = new Thread
        {...(adding new Post item here, not important since this works perfectly)...};
context.Categories.Single(c => c.Name == "some_category").Threads.Add(thr);

但这显然不想工作。

1 个答案:

答案 0 :(得分:1)

您是否实际将新的Thread项添加到您的上下文中以便跟踪它?如果您的上下文不知道它存在,则不会将其添加到数据库中。

var context = new Db();
var thr = new Thread
        {...(adding new Post item here, not important since this works perfectly)...};

//add thread to context
context.Threads.Add(thr);

context.Categories.Single(c => c.Name == "some_category").Threads.Add(thr);