[英]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_1
或1_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.它可以完成工作,但不确定这是否是更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.