首页 > 解决方案 > 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?

标签: entity-frameworkentity-framework-6ef-code-firstef-code-first-mapping

解决方案


这更像是一个黑客然后是清晰的解决方案。可以通过注释来完成[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 的行,那么可能是可行的解决方案。


推荐阅读