【发布时间】:2010-10-23 12:43:19
【问题描述】:
奇怪的问题标题...
我想我想要完成的事情很简单。
我在数据库中有 3 个表,
BlogPost - BlogPostTagsConnection - 标签
blogpost 包含文本、标题、slug、作者、id 等。BlogPostTagsConnection 包含 BlogPost id 和 Tags id,最后 Tags 包含 tagid 和 tag。
所以我试图弄清楚如何插入一条新记录(并最终更新一条):
public void Create(BlogPost post)
{
DB db = new DB();
var matchingTags = from data in db.Tags
where (from tagsInPost in post.Tags select tagsInPost.TagName).Contains(data.Tag)
select new Tag() {TagId = data.TagID, TagName = data.Tag};
var post2 = new DataBlogPost
{
Title = post.Title,
Text = post.Text,
Slug = post.Slug,
ShortDescription = post.ShortDescription,
Published = post.Published,
Author = post.Author
};
db.DataBlogPosts.InsertOnSubmit(post2);
... <- insert the tags and retrieve the id from the tags and the blogpost
... <- insert the ids from the tags and blogposts to the blogpoststagsconnection table
db.SubmitChanges();
}
首先,我从数据库中获取与我在博文中写的标签匹配的所有标签。标签保存在带有标签 { TagID, Tag } 的列表中。
其次,我将我的新帖子插入数据库(post2)。
在此之后我需要插入所有标签(我用我的博文创建的),所以如果我在标签文本框“tag1 tag2 tag3 tag4”中写了这个并且我的数据库已经包含 tag1 和 tag2,那么它应该创建2条新记录,一条用于tag3,一条用于tag4。
然后我需要以某种方式从生成的博客文章中获取 id 以及来自 tag3 和 tag4 的 id 以便能够将它们插入到 BlogPostTagsConnection 中。
但是我如何取回 ID?还是有更简单的方法来处理这些插入?
【问题讨论】:
标签: linq linq-to-sql insert datacontext