【问题标题】:How to access properties of entities in EF Core dynamically?如何动态访问 EF Core 中实体的属性?
【发布时间】:2021-07-20 16:59:01
【问题描述】:

我有一个基类DatabaseContext,它继承自DbContext。我正在尝试集中配置我的实体模型的一些属性。

这是我的DatabbaseContext代码:

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace Company.DataAccess
{
    public abstract class DatabaseContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var allEntities = modelBuilder.Model.GetEntityTypes().Select(p => modelBuilder.Entity(p.ClrType));

            foreach (var entity in allEntities)
            {
                // var properties = entity.GetProperties(); // this line throws exception
                // foreach (var property in properties)
                // {
                //  // if it's Guid, configure it this way
                //  // if it's Enum, configure it this way
                //  // if it's Date, configure it this way
                //  // ...
                // }
            }
        }
    }
}

但是entity.GetProperties()这一行抛出了这个错误:

DatabaseContext.cs:错误 CS1061:“EntityTypeBuilder”不包含“GetProperties”的定义,并且找不到接受“EntityTypeBuilder”类型的第一个参数的可访问扩展方法“GetProperties”(您是否缺少 using 指令或程序集参考?)

如何获取实体模型的属性?

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    正如错误提示,GetProperties 不适用于类型 EntityTypeBuilder。所以你将无法调用它。但是EntityTypeBuilder 作为属性Metadata 可以调用GetProperties。所以试试下面 -

    entity.Metadata.GetProperties();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2017-11-27
      • 2021-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多