c# - 动态创建实体实例并添加新条目

标签 c# entity-framework

请考虑以下示例:

public override int SaveChanges()
{
    foreach (var auditableEntity in ChangeTracker.Entries<ISomething>())
    {
        if (auditableEntity.State == EntityState.Added)
        {
            //Create a new instance of the same entity type. 
            //I don't know which one will be. They just have the same interface.
            var newEntity = ?; //???Reflection???

            //ISomething known properties.
            newEntity.propX = "1";
            newEntity.propY = "2";

            //Invoke Add method.
            ??.Add(newEntity); 
        }
    }

    return base.SaveChanges();
}

我需要在 SaveChanges() 方法期间动态创建我所有 ISomething 实体的实例,以便添加新的特定条目

我们非常欢迎任何帮助。

问候

最佳答案

您可以使用非通用 DbContext.Set Method (Type)得到相应的非通用 DbSet .然后你可以使用Create方法创建相同类型的新实例和Add添加方法。

像这样:

var entityType = auditableEntity.Entity.GetType();
var dbSet = Set(entityType);
var newEntity = (ISomething)dbSet.Create();

//ISomething known properties.
newEntity.propX = "1";
newEntity.propY = "2";

dbSet.Add(newEntity); 

关于c# - 动态创建实体实例并添加新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45182212/

相关文章:

c# - 如何在 Selenium 中获取和设置文本编辑器值

.net - 下载 .NET 3.5 的 Entity Framework

c# - 在哪里使用 EF6 订阅 ObjectMaterialized?

c# - 通过 EF LINQ 比较 UTC 中的 DateTimeOffset?

c# - 取消 HttpClient 请求 - 为什么 TaskCanceledException.CancellationToken.IsCancellationRequested 为假?

C# 随机 BigInt 生成器

sql-server - 多个 Include/ThenInclude 在 EF Core 中导致重复

c# - EntityCommandCompilationException 指定的方法不支持 Entity Framework

c# - 将 soap XML 解析为 C# 类

c# - 需要一些初学者 C# 代码的解释