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

Query Operations

When using an operation like the Where() method in the following code:

Listing 8

_context.Customers.Where(i => i.AccountNumber == "T2341003");

The results that come back are a DataQuery object. This object is not null for queries that even return no results. So the following code works:

Listing 9

customers = _context.Customers.Where(i => i.AccountNumber == "XXXX");
Assert.AreEqual(0, customers.Count());
count = 0;
foreach (Customer customer in customers)
      //Test that iterating through collection is OK
Assert.AreEqual(0, count);

What this means is that the Where() method returns no records, because the account number does not exist. The result count is an empty query, but you can continue to use this object freely, as shown above, and not have to worry about a null reference exception.

View Entire Article

User Comments

Title: Another way to do this...?   
Name: Funka!
Date: 2009-08-14 5:17:13 PM
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.

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

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

©Copyright 1998-2022  |  Page Processed at 2022-08-15 6:44:03 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search