Dynamically Set TEntity Name to DbContext.Set

huangapple go评论64阅读模式
英文:

Dynamically Set TEntity Name to DbContext.Set

问题

I can provide a translation of the code update section you provided:

Type LogType = Type.GetType("UserLogs");
if (LogType != null)
{
    var LogObject = Activator.CreateInstance(LogType);
    if (LogObject != null)
    {
        foreach (PropertyInfo property in LogType.GetProperties())
        {
            if (property.CanWrite)
            {
                if (property.PropertyType == typeof(string))
                {
                    property.SetValue(LogObject, Convert.ToString(Entity.GetType().GetProperty(property.Name)?.GetValue(Entity)));
                }
            }
        }
        var TEntity = _dbContext.Model.GetEntityTypes().First(x => x.Name.Contains("UserLogs"));

        await _dbContext.Set<UserLogs>().AddAsync((UserLogs)LogObject);
    }
}

Please note that this code appears to be dynamically creating an object of type "UserLogs" and adding it to the _dbContext using Entity Framework.

英文:

I am new to C# and Entity Framework. I have a scenario where I want to Insert Record to a Table based on Some Check and Conditions.

The problem is I do not know What Entity would be used to perform Insert/Update operation.

As you can see in Following C# Code I can Add UserLogs and PageLogs Entities in my Repository (Unit Of Work).

await _dbContext.Set&lt;UserLogs&gt;().AddAsync((UserLogs)ObjectChanges);

await _dbContext.Set&lt;PageLogs&gt;().AddAsync((PageLogs)ObjectChanges);

But in my Scenario, I only have String Names of Entities ("UserLogs", "PageLogs") and I can not Assign String Variable to _dbContext.Set&lt;&gt;

I tried to Get TEntityType by using

var TEntity = _dbContext.Model.GetEntityTypes()
    .First(x =&gt; x.Name.Contains(&quot;UserLogs&quot;));

I also have Tried to follow solution given to this Question.

But this also does not work, so I would like to know if there is any solution to this problem where I can DbSet a Dynamic Entity based on String Name.

Code Update

Type LogType = Type.GetType($&quot;UserLogs&quot;);
            if (LogType != null)
            {
                var LogObject = Activator.CreateInstance(LogType);
                if (LogObject != null)
                {
                    foreach (PropertyInfo property in LogType.GetProperties())
                    {
                        if (property.CanWrite)
                        {
                            if (property.PropertyType == typeof(string))
                            {
                                property.SetValue(LogObject, Convert.ToString(Entity.GetType().GetProperty(property.Name)?.GetValue(Entity)));
                            }
                        }
                    }
                    var TEntity = _dbContext.Model.GetEntityTypes().First(x =&gt; x.Name.Contains(&quot;UserLogs&quot;));

                    await _dbContext.Set&lt;$&quot;UserLogs&quot;&gt;().AddAsync(($&quot;UserLogs&quot;)LogObject);
                }
            }

答案1

得分: 1

EF Core没有非泛型的DbSet类。但它并不需要,因为DbContext类提供了所有泛型DbSet&lt;T&gt;方法的非泛型等效方法(除了查询)。

例如,Add(Object)

public virtual EntityEntry Add(object entity);

类似的还有AddAsyncUpdate{Async}Remove{Async}等方法。

它内部使用传递对象的GetType()来确定实体类型(因此确定表)。因此,只要您能传递正确的对象实例(即使在您的原始问题中也必须这样做),就可以使用这些方法执行所需的操作。

例如,使用您的示例:

await _dbContext.AddAsync((object)ObjectChanges);
英文:

EF Core has no non generic DbSet class. But it does not need to, since the DbContext class provides non generic equivalents of all generic DbSet&lt;T&gt; methods (except for querying).

For instance, Add(Object):

>cs
&gt;public virtual EntityEntry Add(object entity);
&gt;

Similar for AddAsync, Update{Async}, Remove{Async} etc.

Internally it uses GetType() of the passed object to determine the entity type (thus table). So as soon as you can pass correct object instances (you need to do that anyway even with your original question), you can use these methods to perform the requested action.

e.g. with your example

await _dbContext.AddAsync((object)ObjectChanges);

huangapple
  • 本文由 发表于 2023年5月25日 20:01:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332037.html
  • c#
  • entity-framework-core

为所有缺失的枚举添加到List中。 go 65
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定

  • 开发者交流平台

    本页二维码