【发布时间】:2020-05-03 14:32:12
【问题描述】:
我喜欢从方法而不是属性向列添加一些数据。这在 EF Core 中是否可行?
例如,配置代码可能如下所示:
internal class MyEntityTypeConfiguration : IEntityTypeConfiguration<MyEntity>
{
public void Configure(EntityTypeBuilder<MyEntity> builder)
{
builder.ToTable("Table1");
// Add column "Value1" and set it with the return value of myEntity.GetValue()
builder.Property<string>("Value1").WithValue(myEntity => myEntity.GetValue()); // TODO create WithValue
builder.HasKey(o => o.Id);
}
}
在这种情况下,WithValue 方法将不存在。
示例:
例如,我将保存 2 个实体。
-
GetValue()对于实体 1 返回"I am Entity 1" -
GetValue()实体 2 返回"I am Entity 2"
然后我喜欢在Value1列中存储"I am Entity 1"和"I am Entity 2"
解决方案
Jairo 使用ValueGenerator 的解决方案非常适合我!我像这样制作了WithValue:
internal class ValueRetriever<TEntityEntry, TResult> : Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator<TResult>
{
private readonly Func<TEntityEntry, TResult> _retrieve;
public ValueRetriever(Func<TEntityEntry, TResult> retrieve)
{
_retrieve = retrieve;
}
public override bool GeneratesTemporaryValues => false;
public override TResult Next(EntityEntry entry) => _retrieve((TEntityEntry)entry.Entity);
}
WithValue分机:
public static void WithValue<TEntityEntry, TResult>(this PropertyBuilder<TResult> propertyBuilder, Func<TEntityEntry, TResult> retrieve)
{
propertyBuilder.HasValueGenerator((property, type) => new ValueRetriever<TEntityEntry, TResult>(retrieve));
}
用法:
builder
.Property<string>("Value1")
.WithValue<MyEntity, string>(myEntity => myEntity.GetValue());
【问题讨论】:
-
您到底想解决什么问题?类型
MyEntity将始终具有相同的值。为什么要保存到数据库中? -
保存多个实体时,值当然会不同
-
好的。我仍然不确定你想要实现什么。你能详细说明一下吗?
-
有一种方法可以将 EF Core 配置为使用 SQL 生成的属性值。
-
添加示例,但也感谢 Jairo Alfaro 的解决方案 :)
标签: c# entity-framework-core entity-framework-core-3.0