【发布时间】:2012-07-18 23:18:11
【问题描述】:
一篇文章可以有多个主题。一个主题可以分配给许多帖子。
添加从主题列表中选择的两个主题的帖子时,两个NULL 主题也插入到我的主题表中。请参阅 Id=34 和 35。我做错什么了?不应更改主题。我正在添加一个新帖子并从固定数量的主题(下拉列表)中选择主题。它在 PostTopics 表(PostID、TopicID)中被跟踪。
主题表:
Id TopicName TopicDesc 31 Sports Sports 32 Game Game 33 Politics Politics 34 NULL NULL 35 NULL NULL
TopicPosts 表:
Topic_Id Post_Id
34 11
35 11
public class Post
{
public int Id { get; set; }
public int UserId { get; set; }
public virtual ICollection<Topic> PostTopics { get; set; }
}
public class Topic
{
public int Id { get; set; }
public string TopicName { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
// insert code: I think the problem is here
using (var context = new ChatContext())
{
// Post
context.Posts.Add(pobjPost);
pobjPost.PostTopics = new List<Topic>();
// topics
foreach (var i in pobjTopics)
{
pobjPost.PostTopics.Add(i);
}
context.SaveChanges();
}
【问题讨论】:
-
包含一些变量的来源代码可能会有所帮助(
pobjPost,pobjTopics) -
它们来自我的 UI 层。我不想让你厌烦细节。
-
不只是
foreach (var i in pobjTopics.Where(t => t.TopicName != null))吗? -
不应更改主题。我正在添加一个新帖子并从固定数量的主题(下拉列表)中选择主题。它在 PostTopics 表(PostID、TopicID)中被跟踪。
标签: c# entity-framework ef-code-first