Skip to content

Conventions

Jeff Treuting edited this page Jun 29, 2013 · 1 revision

SharpRepository uses some conventions by default and we wanted to provide a way for you to customize what those are by overriding the defaults as needed. Currently, the main convention used is for determining which property is the primary key.

To override the conventions on a globally you will make change the properties on the DefaultRepositoryConventions class.

The default implementation for finding the primary key property checks the following:

  1. Checks for a property with the [RepositoryPrimaryKey] attribute set.
  2. Checks for a property named Id (which is the default suffix)
  3. Checks for a property named [ClassName]Id

If you are simply using the naming convention of [ClassName]Key (i.e. ContactKey) instead of [ClassName]Id (i.e. ContactId), then you can change the default PrimaryKeySuffix like so:

DefaultRepositoryConventions.PrimaryKeySuffix = "Key";

Then all of your repositories will look for primary keys that end in Key instead of Id.

For more complex changes you can control the entire method that is called for getting the primary key name. To do this you define a method that takes a single Type parameter (the Type of the entity), and returns a string (the name of the primary key property). Let's say you have a legacy database that has some primary key column names like PK_Contact_Id (where Contact is the name of the entity). You could change the global convention for finding the primary key like so:

DefaultRepositoryConventions.GetPrimaryKeyName = type => "PK_" + type.Name + "_Id";

There may be cases where a single repository does not follow the global rules and you want to change the logic for the primary only for one of the repositories.

// if you want to hard code it and don't need to use the type of the entity you could do this
repos.Conventions.GetPrimaryKeyName = _ => "MyCrazyColumnId";

// or you could still take the type into account and do like before, but only for this repository
repos.Conventions.GetPrimaryKeyName = type => "PK_" + type.Name + "_Id";

Note: you can always use the [RepositoryPrimaryKey] attribute to define it without making this change, or if using the Ef5Repository it will automatically find the primary key based on the EF [Key] attribute as well. But that is a bit of a tangent I guess.

Clone this wiki locally