Skip to content

Instantly share code, notes, and snippets.

@ravindUwU
Last active August 26, 2024 14:59
Show Gist options
  • Save ravindUwU/db88dfef74656b9648d2d0aa0eb7f50f to your computer and use it in GitHub Desktop.
Save ravindUwU/db88dfef74656b9648d2d0aa0eb7f50f to your computer and use it in GitHub Desktop.
// Context:
// - Invoked within `OnModelCreating(ModelBuilder modelBuilder)`.
// - `entity` is an `IMutableEntityType`, obtained by iterating `modelBuilder.Model.GetEntityTypes()`.
// - `builder` is an `EntityTypeBuilder`, obtained by calling `modelBuilder.Entity(string name)`.
// Find [Key] properties of the entity.
var keys = entity.GetProperties()
.Where((p) => p.PropertyInfo?.GetCustomAttribute<KeyAttribute>() is not null)
.ToList();
// If the entity has a composite key, register it with `EntityTypeBuilder.HasKey`.
if (keys.Count > 1)
{
// Group [Key]s by their [Column] order.
var columnOrders = keys
.Where((p) => p.PropertyInfo is not null)
.GroupBy((p) => p.PropertyInfo!.GetCustomAttribute<ColumnAttribute>()?.Order
?? throw new Exception("[Column(Order = ?)] must be specified on all [Key]s.")
);
// Ensure that [Key]s are of distinct [Column] orders (i.e., groups can't have > 1 column),
var badColumnOrders = columnOrders.Where((g) => g.Count() > 1);
if (badColumnOrders.Any())
{
var m = String.Join(", ", badColumnOrders.Select((g) => $"Order {g.Key}: [{String.Join(", ", g.Select((p) => p.Name))}]"));
throw new Exception($"[Key]s must be ordered distinctly. {m}");
}
// Define ordered composite key for the entity.
var key = columnOrders
.OrderBy((g) => g.Key)
.Select((g) => g.Single().Name)
.ToArray();
builder.HasKey(key);
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class MyTable
{
[Key]
[Column(Order = 0)]
public string Key1 { get; set; } = default!;
[Key]
[Column(Order = 1)]
public string Key2 { get; set; } = default!;
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment