Sol*_*ake 2 c# entity-framework entity-framework-core
我正在尝试将数据应用于模型中builder.Property(_ => _.[DYNAMIC_FIELD_NAME]).HasComment("Some comment")具有属性的所有属性。Description到目前为止,这是我使用反射的尝试:
public class User : TableFieldsBase, IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
var tableName = this.GetType().Name;
builder.ToTable(tableName);
var props = GetType().GetProperties();
foreach(var prop in props)
{
var descriptionAttr = this.GetAttributeFrom<DescriptionAttribute>(prop.Name);
if(descriptionAttr != null)
{
builder.Property(t => EF.Property<object>(t, prop.Name)).HasComment(descriptionAttr.Description);
}
}
}
[Description("This is the username")]
public string Username { get; set; }
[DisplayName("Email")]
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在循环访问模型的所有属性并提取它们的描述文本。例如,Username有一个描述属性,我想用它来将其保存在数据库的“评论”字段中。这里的问题是我不确定如何在builder.Property方法中动态应用该属性。也许我以错误的方式看待它?
这是我运行此代码时遇到的错误:
Exception has occurred: CLR/System.ArgumentException
Exception thrown: 'System.ArgumentException' in Microsoft.EntityFrameworkCore.dll: 'The expression 't => Property(t, value(Backend.Classes.Api.Avpf.Core.Models.User+<>c__DisplayClass0_0).prop.Name)' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'.'
at Microsoft.EntityFrameworkCore.Infrastructure.ExpressionExtensions.GetPropertyAccess(LambdaExpression propertyAccessExpression)
at Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.Property[TProperty](Expression`1 propertyExpression)
at Backend.Classes.Api.Avpf.Core.Models.User.Configure(EntityTypeBuilder`1 builder) in Models\User.cs:line 38
Run Code Online (Sandbox Code Playgroud)
提前致谢。
只需使用Property带有参数的方法重载string propertyName:
builder.Property(prop.Name)
.HasComment(descriptionAttr.Description);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
777 次 |
| 最近记录: |