简体   繁体   English

如何从 EF Core 中的实体属性生成自定义 ID?

[英]How to generate custom Id from entity properties in EF Core?

I have a scenario that I have to generate an Id based on the two properties of an Entity.我有一个场景,我必须根据实体的两个属性生成一个 Id。 For instance:例如:

public class Foo
{
    public string Id { get; set; }
    
    public int BarId { get; get; }
    
    public int WafuId { get; set; }
}

The Id should be having a value of {BarId}_{WafuId} , so it could be 1_1 or 1_2 and should be injected every time a record is created. Id 的值应该是{BarId}_{WafuId} ,因此它可以是1_11_2并且应该在每次创建记录时注入。

I have remove the default value generation from the database by doing the this line of code: builder.Property(p => p.Id).ValueGeneratedNever();我已经通过执行这行代码从数据库中删除了默认值生成: builder.Property(p => p.Id).ValueGeneratedNever(); . . And then tried the ValueGenerator然后尝试了 ValueGenerator

public class FooIdValueGenerator : ValueGenerator<string>
{
    public override string Next(EntityEntry entry)
    {
        var ent = new Foo();
        var barIdPropName = nameof(ent.BarId);
        var wafuIdPropName = nameof(ent.WafuId);
        
        var id1 = entry.CurrentValues[barIdPropName];
        var id2 = entry.CurrentValues[wafuIdPropName];

        return $"{id1}_{id2}";
    }

    public override bool GeneratesTemporaryValues { get; }
}

It does the job, but not sure if this is the better approach.它可以完成工作,但不确定这是否是更好的方法。

With the fluent API notation, you can use a computed SQL column like this:使用流畅的 API 表示法,您可以使用计算得到的 SQL 列,如下所示:

 builder.Property(e => e.Id)
        .HasComputedColumnSql("[BarId] + '_' + [WafuId]");

You can also take a look at this example .你也可以看看这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM