Linq to sql Inserting Attached Entity Objects

360 views Asked by At

I'm learning Linq to sql and I came across "Inserting Attached Entity Objects" I have tested example from the book and it works fine but could someone explain me how to edit it to make it work for my example

I have two tables (I'll ignore userID in this example)

Topics -> TopicID, Title

Posts -> PostID, TopicID, Content

Now when user creates new topic I have to create new Topic which contains details about it and new post which contains details about that post, however, problem is that I have to insert these two tables into database at once as I dont want to have Topic and no post assign to it.

I have code which works fine if I set TopicID manually, however I would like to live it free so it is assigned automatically

            Topic topic = new Topic
                            {
                                TopicID = 1, //how to remove this line
                                Title = "Test", 
                                Post = new Post
                                    {
                                        TopicID = 1, // and this one
                                        Content = "some text",
                                    }
                            };

So to resume I would like to remove these two lines so TipicID is generated automatically and both records are inserted into database or none is

EDIT:

LooL, I have tested it once again and seems like this code works fine if I just comment these two lines, but could someone explain me what will happen in case is topic is inserted into database but computer suddenly shuts down and post is left unsaved in database. Will it role back and delete topic or I'll have topic with no post in database?

1

There are 1 answers

0
Scott Munro On

You should skip explicitly setting the TopicID and build the relationship using the Topic property (an object reference to an instance of Topic rather than the ID).

That would look like this.

Topic topic = new Topic                            
{                                
    Title = "Test"                                                         
};

Post = new Post                                    
{                                        
    Topic = topic,
    Content = "some text"
};