简体   繁体   中英

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. 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.

I have remove the default value generation from the database by doing the this line of code: builder.Property(p => p.Id).ValueGeneratedNever(); . And then tried the 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:

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

You can also take a look at this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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