Knight Data Access Layer
Composite Keys
Basic Tasks C# > Mapping > Composite Keys

Composite Keys Overview

The highest performance is gained when using an integer or long primary key in a database.  Some legacy databases may require the use of composite keys.  Implement an IsNew property on your class so that it can be determined when an insert or update needs to occur.  See Using IsNew for more information.

 

Mapping with Attributes

[CompositeKey]

public string Region { get; set; }

[CompositeKey]

public string Salesman { get; set; }

 

Mapping with Code

IDataHelper db = DataHelper.SessionFactory();

Table table = new Table(typeof(SalesPeople));

table.TableName = "SalesPeople";

Field field = new Field(table, "Salesman", "Salesman");

field.IsCompositeKey = true;

table.Fields.Add(field);

field = new Field(table, "Region", "Region");

field.IsCompositeKey = true;

table.Fields.Add(field);

db.Mapper.ObjectMap.Add(typeof(Person), table);

 

Mapping with XML

<Table>
 <MappingFromDatabase>false</MappingFromDatabase>
 <Schema />
 <ClassTypeString>Models.SalesPeople, NET-Data-Access-Layer-Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</ClassTypeString>
 <ClassName>SalesPeople</ClassName>
 <TableName>SalesPeople</TableName>
 <Fields>
   <Field>
  <ColumnName>Salesman</ColumnName>
  <PropertyInfoString>Salesman</PropertyInfoString>
  <FieldTypeString>System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</FieldTypeString>
  <DatabaseType>string</DatabaseType>
  <Unique>false</Unique>
  <AllowDbNull>false</AllowDbNull>
  <IsPrimaryKey>false</IsPrimaryKey>
  <KeyType xsi:nil="true" />
  <IsReadOnly>false</IsReadOnly>
  <Length xsi:nil="true" />
  <IsCompositeKey>true</IsCompositeKey>
  <IsMaintenanceField>false</IsMaintenanceField>
   </Field>
   <Field>
  <ColumnName>Region</ColumnName>
  <PropertyInfoString>Region</PropertyInfoString>
  <FieldTypeString>System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</FieldTypeString>
  <DatabaseType>string</DatabaseType>
  <Unique>false</Unique>
  <AllowDbNull>false</AllowDbNull>
  <IsPrimaryKey>false</IsPrimaryKey>
  <KeyType xsi:nil="true" />
  <IsReadOnly>false</IsReadOnly>
  <Length xsi:nil="true" />
  <IsCompositeKey>true</IsCompositeKey>
  <IsMaintenanceField>false</IsMaintenanceField>
   </Field>  
 </Fields>
</Table>