LINQ to SQL PK Relationships

LINQ to SQL maintains object relationships between all tables, mimicing how the database looks.  What I mean by that is that you can drill down (or up) through a database hierarchy in an object-oriented fashion, simply by referencing the property.  So an Employee class with a PK of Manager could reference that manager via:

employeeInstance.Manager

Provided that relationship is not null.  Suppose there is a relationship that is null, which is State.  State is a reference table related to Employee, but sometimes the employee address isn't entered into the system when the employee name/ID is.  So, the state can be null.  In LINQ, State is represented by two properties:

State = the LINQ class reference to the state record, if not null.
StateKey = the key to the class record in the state table.

If in LINQ, you write code that says:

employee.StateKey = 1;

The StateKey is set to 1, but the State reference value is null until you call SubmitChanges() on the DataContext.  However, the other way around is not true; you can assign a state object like:

employee.State = this.Context.States.Single(i => i.StateKey == 1);

This assigns the State reference, but StateKey is also assigned to the key of the state object.

Published Sunday, March 30, 2008 5:12 AM by bmains
Filed under:

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.