简体   繁体   English

如何将动态实体设置为 dbcontext Entity Framework Core?

[英]How to set dynamic entity to dbcontext Entity Framework Core?

I got a method that receives an entity like string to return a list of that entity.我得到了一个方法,它接收一个像 string 这样的实体来返回该实体的列表。

What I want is set the entity dynamically and return the result.我想要的是动态设置实体并返回结果。

What I need is something like this:我需要的是这样的:

DbContext.Set <Type.GetType("Entity")>().Select(e => e);

This the error that I getting:这是我得到的错误:

错误

Maybe this is not the correct to do so.也许这不是正确的做法。

The Set method comes from Entity Framework Core. Set方法来自 Entity Framework Core。

设置方法

You Can Use Generic type Like Below:您可以使用如下的通用类型

DbContext.Set<T>().Select(e => e);

but For this Your Method Should Works With Generics Like Example at below (This Code Not Tested ):但为此,您的方法应该适用于下面的示例(此代码未测试):

public Task<object> MyMethod<T>(T model)
{
   // some Code
}

You Can Learn more About it in This Link您可以在此链接中了解更多信息

Sorry For Bad English.抱歉英语不好。 I Wish its Helps ...我希望它的帮助...

1st - this is an example, not a solution for your specific problem.第一 - 这是一个例子,不是您特定问题的解决方案。

My entity class我的实体类

using System;
using System.Collections.Generic;
using System.Text;

namespace MyIdentityModel
{
    public class IdentityRole
    {
        public long Id { get; set; } 
        public string Name { get; set; } = null!;
        public DateTimeOffset CreatedAt { get; set; }
        public bool Active { get; set; }
        public bool Enabled { get; set; }
        public DateTimeOffset ActiveUntil { get; set; }

    }
}

My Context我的背景

using MyIdentityModel.Configuration;
using Microsoft.EntityFrameworkCore;
using System;

namespace MyIdentityModel
{

    public abstract class IdentityDbContextBase: DbContext
    {

        public IdentityDbContextBase(DbContextOptions options) : base(options)
        {
        }

        
        public DbSet<IdentityRole> Roles { get; set; } = null!;
        

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
                        modelBuilder.ApplyConfiguration(new IdentityRoleConfiguration());
           
        }
    }
}

Example Solution示例解决方案
I have 3 approachs我有 3 种方法

public List<TResult> GetList<TResult>(DbContext context, string entityTypeName)
    where TResult : class
{
    Type entityType = Type.GetType(entityTypeName); // get type of entity / MyIdentityModel.IdentityRole
    var setMethod = context.GetType().GetMethod(nameof(DbContext.Set), new Type[] { }).MakeGenericMethod(entityType); //Get Method Set<MyIdentityModel.IdentityRole>
    var dbSet = setMethod.Invoke(context, new object[] { }); // Calling context.Set<MyIdentityModel.IdentityRole>
    /* Call to another methods using reflection before calling "ToList" 
        Eg. example Where, Include, Select
        */
    var toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(entityType); //get Extension Method "ToList<MyIdentityModel.IdentityRole>"
    var list = (List<TResult>)toListMethod.Invoke(null, new object[] { dbSet });//Calling "context.Set<MyIdentityModel.IdentityRole>.ToList<MyIdentityModel.IdentityRole>()" Method and convert to destination type if is possible.
    return list;
}

public List<TEntity> GetList2<TEntity>(DbContext context)
    where TEntity : class
{
    var setMethod = context.GetType().GetMethod(nameof(DbContext.Set), new Type[] { }).MakeGenericMethod(typeof(TEntity)); //Get Method Set<MyIdentityModel.IdentityRole>
    var dbSet = setMethod.Invoke(context, new object[] { }); // Calling context.Set<MyIdentityModel.IdentityRole>
    /* Call to another methods using reflection before calling "ToList" 
        Eg. example Where, Include, Select
        */
    var toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(typeof(TEntity)); //get Extension Method "ToList<MyIdentityModel.IdentityRole>"
    var list = (List<TEntity>)toListMethod.Invoke(null, new object[] { dbSet });//Calling "context.Set<MyIdentityModel.IdentityRole>.ToList<MyIdentityModel.IdentityRole>()" Method and convert to destination type if is possible.
    return list;
}

public List<TEntity> GetList3<TEntity>(DbContext context)
    where TEntity : class
{
    return context.Set<TEntity>()/* Call to another methods before "ToList" */.ToList();
}


the main program calls.主程序调用。

  1. Yo need the context, AssemblyQualifiedName = parameters .你需要上下文, AssemblyQualifiedName = parameters The type name of result = type parameters .结果的类型名称=类型参数

public List<TResult> GetList<TResult>(DbContext context, string entityTypeName)

  1. Yo need the context = parameters .你需要 context = parameters The type name of result = type parameters .结果的类型名称=类型参数

public List<TEntity> GetList2<TEntity>(DbContext context)

  1. Yo need the context = parameters .你需要 context = parameters The type name of result = type parameters .结果的类型名称=类型参数

public List<TEntity> GetList3<TEntity>(DbContext context)

Console.WriteLine("█ Result 1");
var result = GetList<MyIdentityModel.IdentityRole>(context, typeof(MyIdentityModel.IdentityRole).AssemblyQualifiedName);
Console.WriteLine(JsonSerializer.Serialize(result));
Console.WriteLine();

Console.Write("█ Result 2");
var result2 = GetList2<MyIdentityModel.IdentityRole>(context);
Console.WriteLine(JsonSerializer.Serialize(result2));
Console.WriteLine();

Console.Write("█ Result 3");
var result3 = GetList3<MyIdentityModel.IdentityRole>(context);
Console.WriteLine(JsonSerializer.Serialize(result3));
Console.WriteLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心 DbContext 设置 DbConnection - Entity Framework Core DbContext set DbConnection 如何刷新 Entity Framework Core DBContext? - How to refresh an Entity Framework Core DBContext? 如何在 Entity Framework Core 中处理 DBContext 实例化 - How to handle DBContext instancing in Entity Framework Core 实体框架DBContext和动态ConnectionString - Entity Framework DBContext and dynamic ConnectionString 从 Entity Framework Core 中的实体获取 DbContext - Get DbContext from Entity in Entity Framework Core 有没有办法使用连接工厂设置实体框架核心 DbContext? - Is there a way to set up an Entity Framework Core DbContext with a connection factory? 如何在实体框架核心中创建DBContext作为现有事务的一部分 - How to create a DBContext as part of an existing transaction in Entity Framework Core 如何使用 Entity Framework Core 将现有存储过程添加到 dbcontext - How to add an existing stored procedure to dbcontext with Entity Framework Core 如何刷新 Entity Framework Core DbContext 但保留我的属性装饰? - How to refresh Entity Framework Core DbContext but keep my property decorations? 如何将存储过程添加到 Entity Framework Core DbContext? - How to add stored procedures to Entity Framework Core DbContext?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM