Skip to content

Instantly share code, notes, and snippets.

@jamie94bc
Created January 17, 2016 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamie94bc/3fd32badb9211b37f378 to your computer and use it in GitHub Desktop.
Save jamie94bc/3fd32badb9211b37f378 to your computer and use it in GitHub Desktop.
Things EntityFramework 6's DbModelBuilder is missing or could be more succinct.
/// <summary>
/// Things <see cref="DbModelBuilder"/> is missing or could be more succinct.
/// </summary>
public static class DbModelBuilderExtensions {
/// <summary>
/// Configures the primary key property for this entity type.
/// </summary>
/// <typeparam name="TEntityType"></typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="keyExpression">A lambda expression representing the property to be configured.</param>
/// <param name="databaseGeneratedOption">
/// The pattern used to generate values for the property in the database. Setting
/// 'null' will cause the default option to be used, which may be 'None', 'Identity',
/// or 'Computed' depending on the type of the property, its semantics in the model
/// (e.g. primary keys are treated differently), and which set of conventions are
/// being used.
/// </param>
public static EntityTypeConfiguration<TEntityType> HasKey<TEntityType, TKey>(
this EntityTypeConfiguration<TEntityType> config,
Expression<Func<TEntityType, TKey>> keyExpression,
DatabaseGeneratedOption databaseGeneratedOption
)
where TEntityType : class
where TKey : struct
{
config.HasKey(keyExpression);
config.Property(keyExpression).HasDatabaseGeneratedOption(databaseGeneratedOption);
return config;
}
/// <summary>
/// Registers an entity type as part of the model and calls a callback to configure the entity.
/// </summary>
/// <param name="config">The configuration action.</param>
public static void Entity<TEntityType>(this DbModelBuilder builder, Action<EntityTypeConfiguration<TEntityType>> config) where TEntityType : class {
config(builder.Entity<TEntityType>());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment