views:

18

answers:

2

Wierd question title...

What i am trying to accomplish is pretty simple i think.

I got 3 tables in the database,

BlogPost - BlogPostTagsConnection - Tags

The blogpost contains text, title, slug, author, id etc. The BlogPostTagsConnection contains the BlogPost id and the Tags id and finally the Tags contains tagid and tag.

So i tried to figure out how to insert a new record (and eventually to update one):

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

First i am getting all the tags from the database that matches the tags that i wrote in my blogpost. The tags are saved in a List with Tags { TagID, Tag }.

Secondly i insert my new post into the database (post2).

After this i need to insert all the tags (that i have created with my blogpost), so if i wrote this in the tags textbox "tag1 tag2 tag3 tag4" and my database already contains tag1 and tag2, it should then create 2 new records, one for tag3 and one for tag4.

I then need to get the id from the generated blogpost somehow and also the id from the tag3 and tag4 to be able to insert those into the BlogPostTagsConnection.

But how do i get the ID back? or is there a simpler way to handle these inserts?

+1  A: 

Yes, if your FK relationships are properly set up and tables properly imported on your DBML surface, your DataBlogPost will have a property BlogPostTagsConnections (or similar) which you can populate with new (or existing, pulled from the same DataContext) BlogPostTagsConnection instances.

Similarly BlogPostTagsConnection will have a property Tags which you can populate.

When done, insert your DataBlogPost and all the relational data will be saved too. No need to worry about IDs, just add existing or new instances to these "relational" properties.

spender
A: 

spender is right,

and some additional information on how to retrieve the inserted entity id:

After inserting the entity, simply read the ID property for that entity, it'll be fulfilled.

Rami Shareef