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

Automatic Primary Keys

SQL Server supports the auto-generation of primary key values through the identity setting.  When creating a new LINQ business object, the value of the primary key is zero; meaning no value has been assigned. Calling SubmitChanges on the DataContext refreshes this value with the auto-generated value assigned from the backend database. Let us take a look at an example.

When creating a new business object, the value of the primary key is illustrated below.

Listing 6

Product product = new Product();
product.Name = "Value";

//Assign remaining values.

Listing 7

Assert.AreEqual(0, product.ProductKey);

But after the call to submit changes, the value is updated to:

Assert.AreEqual(6, product.ProductKey);

The product key is assigned to an actual value after the product is refreshed.

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:21:32 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search