开发者

Adding related items using Linq to SQL

I have a database with 'transactions' and 'transaction_lines'. A transaction has the basic shared details, and the transaction lines holds the values of components that make up the transaction. In traditional SQL, I'd use a SQL Transaction (Sorry, we have an ambiguous word now...) and then I'd INSERT INTO Transaction ... get the IDENTITY key value from the new row in the transaction table, then insert into my transaction_line table, using the identity column from the Transaction table as the foreign key.

Is there a good way to do this with linq?

Here's what I have so far:

account_transaction ac = new account_transaction
                             {
                                 transaction_date = DateTime.Now,
                                 is_credit = isCredit,
                                 account = (db.accounts.FirstOrDefault(a => a.account_id == accountid))
                             };

db.AddToaccount_transaction(ac);

db.SaveChanges();

I think inbetween the 'AddToaccount_transaction(ac)' and the 'db.SaveChanges()', I need to ad开发者_如何学编程d my transaction_lines.


You should just be able to create new transaction_line objects and set the foreign entity to ac. In LINQ-to-SQL, you work with entity objects instead of explicit keys. By setting the entity object to the ac object you will instruct the layer to determine what the key is and set it for you.


Answer above is correct but I would wrap it all in a TransactionScope. That way if any part of that query fails it will roll back the transaction. Just remember to call the scope.Complete() method prior to closing connection. http://msdn.microsoft.com/en-us/library/ms251686(VS.80).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜