Retrieve the primary key (including composite keys) from any entity as a dictionary.
EF version | .NET support | NuGet package |
---|---|---|
6.1.3 | >= Framework 4.6.1 | |
Core 2.0 | >= Framework 4.6.1 || >= Standard 2.0 |
public class QuestionTag {
[Key, Column(Order = 0)] public Guid QuestionId { get; set; }
[Key, Column(Order = 1)] public Int64 TagId { get; set; }
public DateTime Inserted { get; set; }
}
var primaryKey = questionTag.GetPrimaryKey();
var questionId = (Guid) primaryKey[nameof(QuestionTag.QuestionId)];
var tagId = (Int64) primaryKey[nameof(QuestionTag.TagId)];
var primaryKeyDict = context.GetPrimaryKey(entity);
var primaryKeyDict = entity.GetPrimaryKey(); // auto-detects your DbContext class
var primaryKeyDict = entity.GetPrimaryKey(context);
var primaryKeyDict = entity.GetPrimaryKey<YourDbContext, YourEntity>();
The extension methods provide four different ways to get the primary key, but internally they run mostly the same code. The names of the properties are retrieved from the DbContext metadata, and a fast delegate is cached for each entity type when that type is first used. When the fast delegate is invoked with an entity, it creates a ReadOnlyDictionary<K, V>
where the keys are the names of the properties which comprise that entity's primary key and the values are the value of each corresponding property.
- Create an issue
- Let's find some point of agreement on your suggestion.
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D