1

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?

4

2 回答 2

1

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

于 2018-09-25T15:03:03.507 回答
0

没有“开箱即用”的解决方案。如果您想这样做,您需要创建自己的 Id 值分配器。一旦我们首先使用 EF 代码,更好的方法是覆盖 SaveChanges 方法。在那里您可以检查实体状态和类型,如果它是您添加状态的实体,那么您检查它的 ID。如果它等于 0,您需要从 DB 中获取最大的 Id 并增加它。并且您需要在手动分配时检查重复的 ID。

于 2018-09-25T14:22:25.827 回答