LINQ to SQL Instantiation
page 3 of 8
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40743/ 115

Adding Child Objects

When adding a child LINQ object through its parent object's collection, this does not mean that the object is immediately available through the data context.  For instance, take a look at the following code.

Listing 3

Customer customer = _context.Customers.First();
customer.Orders.Add(order);
Assert.AreEqual(1, customer.Orders.Count());
Assert.AreEqual(++changeCount, _context.GetChangeSet().Inserts.Count);
Assert.AreEqual(0, _context.Orders.Count());

Even though the object is added to the customer's orders collection, the order is not immediately available through the DataContext object (represented by the "_context" variable). Rather, it is listed in the ChangeSet object returned from the GetChangeSet() method. The ChangeSet object contains a collection of the inserted, deleted, and updated objects not yet submitted to the database, which this orders object is one of them.  After the following:

Listing 4

_context.SubmitChanges();
Assert.AreEqual(0, _context.GetChangeSet().Inserts.Count());
Assert.AreEqual(1, customer.Orders.Count());
Assert.IsNotNull(customer.Orders.SingleOrDefault(o => 
     o.ReferenceNumber == "X4590X"));

The order being added is no longer in the change set; it is not a child of the customer object and readily available in the orders table.


View Entire Article

User Comments

Title: Another way to do this...?   
Name: Funka!
Date: 2009-08-14 5:17:13 PM
Comment:
Another possibility it seems is to create a partial class and partial method "OnCreated" ?
For example:
public partial class Order
{
partial void OnCreated()
{
_OrderKey = Guid.NewGuid();
_CreatedDate = DateTime.Now;
}
}
This way, you don't need to keep remembering to do this every time you instantiate an object.

It should also be noted that you avoid your specific error (but not the general need for setting default values) by setting the LTS entity property's "Auto Generated Value" to true --- LTS will know not to supply a value to these columns when inserting, so you can just let SQL server fill in these defaults.

Thanks!
-f!
Title: Great Article !!!   
Name: Jash
Date: 2009-04-13 3:24:14 PM
Comment:
Thank you Brian really useful article.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 4:45:49 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search