EntityFramework.PrimaryKey
Retrieve the primary key (including composite keys) from any entity
Install / Use
/learn @NickStrupat/EntityFramework.PrimaryKeyREADME
EntityFramework.PrimaryKey
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 |
|
Usage
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)];
API
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>();
How it works
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.
Contributing
- 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
History
License
Related Skills
node-connect
345.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
106.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
345.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
345.9kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
