【问题标题】:Where is metadataworkspace in Entity Framework core?Entity Framework 核心中的元数据工作区在哪里?
【发布时间】:2019-01-10 05:15:27
【问题描述】:
我正在尝试使用 Fluent API 在 EntityFramework Core 中设置的反射来读取自定义属性。我做了一些研究,发现 MetadataWorkspace 可以按照以下链接的建议提供帮助:Link 1、Link 2。所有这些解决方案都在 EntityFramework 上。
如何在 EntityFramework Core 中使用 metadataworkspace?
或者,在 Asp.Net Core 2.1 和 EntityFramework Core 上是否有任何解决方案可以在运行时读取 Fluent API 设置的配置属性?
【问题讨论】:
标签:
asp.net-core
entity-framework-core
ef-fluent-api
【解决方案1】:
EF 核心没有 MetadataWorkspace
要获取 EF Core Fluent API 设置的注释,请使用以下示例:
public class Basic {
public int Id {get; set;}
public string Value {get; set;}
}
public class BasicConfig {
public void Configure(EntityTypeBuilder<Basic> builder)
{
builder.ToTable("Basic");
builder.HasKey(e => e.Id)
.HasName("PK_Basic");
builder.Property(e => e.Value)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("Value");
}
}
/// <summary>
/// Returns the MaxLength of a PropertyInfo (field) off of a Custom EF modal Type
/// </summary>
public int DetermineSize(Type basicModelType) {
IEntityType fake = _context.Model.FindEntityType(basicModelType);
IProperty prop = fake.GetProperty("Value");
IEnumerable<IAnnotation> ann = prop.GetAnnotations();
int maxSize = (int)ann.SingleOrDefault(item => item.Name.Equals("MaxLength"))?.Value;
return maxSize;
}