entity-framework - Custom key with autoincrement
问题描述
I have an entity with
entity.Property(f => f.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
because for some reason, I need to enter some id's manually. is it possible to automatically add the next available id (int) if the id is not provided (equal to 0)?
It should work like an Identity field but with the possibility to define the id manually in some special cases.
EDIT :
Is it possible to define the ID's manually when we're migrating the data from an existing database to a new one with the ID field as primary key in the new one?
After some talks, it apprears that we'll need to add some entries with custom ID's only 1 or 2 times by year.
The solution provided by Kamil Folwarczny is interresting but is it better to use this hack or (if the migration with defined ID's is possible), migrate the data 1 or 2 times by year with a maintenance?
解决方案
这更像是一个黑客然后是清晰的解决方案。可以通过注释来完成[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
您可以创建如下内容:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Key]
public int Id
{
get {
if (_id == 0)
{
using (Context context = new Context())
{
return context.DbSetOfEntity.OrderBy(s => s.Id).ToList().Last().Id + 1;
}
}
else
{
return _id;
}
}
set {
_id = value;
}
}
[NotMapped]
private int _id;
现在,如果您Id
从表单提供,它将正常保存您指定的 ID。但是,如果您Id
留空(因为 0 int
)。它将Id
在表中找到最后一次使用并将其递增 1。
一旦实体被创建,它将保持其值,无论是生成的还是指定的。
编辑
如果您每年只需要插入几次具有自定义 ID 的行,那么这可能是可行的解决方案。
推荐阅读
- html - 更改数据表语言时如何避免闪烁或闪烁?
- c++ - 为什么 VideoCapture 在成员函数中不起作用?
- asp.net - 向上舍入的十进制值
- nexus - 我们可以在 Windows 中挂载 Nexus 存储库吗
- sql-server - cast() 有什么好处
- c# - 异步运行长同步操作
- ubuntu - 如何利用 Google Cloud VM Instance 中的所有磁盘空间?
- graphql - 具有动态键的对象的 GraphQL 模式类型
- ruby-on-rails - Ruby on rails 和 crm
- react-native - npm install --save react-google-recaptcha 在应用程序中使用时失败