Manually Setting Up Associations in POCO

by 

| September 22, 2011 | in

When manually writing Plain Old CLR Objects (POCOs) (that is, not using the T4 template mechanism), you’ll be left with not only replicating the structure of the table itself in the object layout, but also any objects associated with said structure (foreign keys).

As an example, note the following association:

Associations in POCO1

The SalesTerritory object, even though the Customer object technically has a foreign key to it, must also maintain a List <Customer> property named “Customers”. If you do not do this, the type will not be recognized properly and the runtime will not be able to use it as a valid POCO DB object.

Interestingly enough, the TerritoryID value (within the Customers entity above), refers to the SalesTerritory table in the database; however, there is also a SalesTerritory object within the Customer’s navigation properties. This all must be reflected as well (even though it’s slightly redundant).

Failing to do any of this will result in odd errors.

The following code illustrates the above associations as POCO objects:

Code illustrates the above associations as POCO objects.

Code illustrates the above associations as POCO objects.


Related posts