【问题标题】:Fill modelBuilder.Entity with dynamic values in dbcontext用 dbcontext 中的动态值填充 modelBuilder.Entity
【发布时间】:2021-08-12 22:54:47
【问题描述】:

我有很多意见,我必须使用(在OnModelCreating asp.net core 5中)

modelBuilder.Entity <y1> (). HasNoKey (). ToView (null); 
... 
modelBuilder.Entity <yn> (). HasNoKey (). ToView (null);

有没有办法动态设置实体值?

modelBuilder.Entity <MyClass1> (). HasNoKey (). ToView (null); 
... 
modelBuilder.Entity <MyClassn> (). HasNoKey (). ToView (null);

我尝试了几种方法,但得到以下错误 =>y1 是类型,但用作变量

get items => foreach (var entity in modelBuilder.Model.GetRootEntityTypes())

【问题讨论】:

  • 什么是GetRootEntityTypes()?还请显示给您相关错误的代码。

标签: asp.net-core entity-framework-core dbcontext asp.net-core-5.0


【解决方案1】:

我猜你正在使用EF 5.0,你是否尝试过使用Shared-Type Entity Types

EF Core 5.0 允许将相同的 CLR 类型映射到多个不同的实体类型;此类类型称为共享类型实体类型。虽然任何 CLR 类型都可以使用此功能,但 .NET Dictionary 提供了一个特别引人注目的用例,我们称之为“属性包”:

public class ProductsContext : DbContext
{
    public DbSet<Dictionary<string, object>> Products => Set<Dictionary<string, object>>("Product");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.SharedTypeEntity<Dictionary<string, object>>("Product", b =>
        {
            b.IndexerProperty<int>("Id");
            b.IndexerProperty<string>("Name").IsRequired();
            b.IndexerProperty<decimal>("Price");
        });
    }
}

更新: TEntity 是一个类而不是一个类型。 我还没有测试过,但也许这可以提供一些启示:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            foreach (var eType in modelBuilder.Model.GetEntityTypes())
            {
                EntityTypeBuilder x = modelBuilder.SharedTypeEntity<Dictionary<string, object>>(eType.Name, b =>
                {
                    foreach (var p in eType.GetProperties())
                    {
                        if(p.GetType() == typeof(int))
                        {
                            b.IndexerProperty<int>(p.Name);
                        }
                        else if(p.GetType() == typeof(string))
                        {
                            b.IndexerProperty<string>(p.Name);
                        }
                        
                    }
                   
                }).SharedTypeEntity(eType.Name, eType.GetType());

                x.HasNoKey();

            }
        }

【讨论】:

  • 感谢您的好意。但我无法得到输出。如果您可以发表评论,我添加了一张照片
【解决方案2】:
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
    modelBuilder.Entity(entity.ClrType).HasNoKey().ToView(null);
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
相关资源
最近更新 更多