0

我有这样的事情:

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);

但这显然不想工作。

4

1 回答 1

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);
于 2012-08-12T18:37:25.360 回答