使用反射和实体

Working with reflection and entities

我正在尝试编写一些逻辑以根据动态 table 值从数据库中获取实体值。按照这个 post 让我达到了 TEntity Entity framework - get entity by name

的地步

我没有听懂这里所说的内容。以下代码:

public static void PublishTable(string user, ContentFields tableToPublish)
        {
            var jsonData = DataAccess.GetEnvironmentJson((int)Environments.Production);
            var model = JsonConvert.DeserializeObject<Models.FullDataSetModel>(jsonData);
            using (var db = new LoginPageContentEntities())
            {
                var deployEntry = db.Deployment.Find((int)Environments.Production);
                deployEntry.DateUpdated = DateTime.Now;

                var pendingChangesFlag = deployEntry.GetType().GetProperty(tableToPublish.ToString());
                pendingChangesFlag.SetValue(deployEntry, false);

                var publishToModel = model.GetType().GetProperty(tableToPublish.ToString());
                var tableValue = (IEnumerable<????>)typeof(LoginPageContentEntities).GetProperty(tableToPublish.ToString()).GetValue(db, null));
                publishToModel.SetValue(model, tableValue.ToList());

                var json = JsonConvert.SerializeObject(model);
                deployEntry.JsonCache = json;
                db.SaveChanges();
            }
        }

例如,如果我在 IEnumerable<ProductInformation> 中传递 ProductInformation 的实体,这在我更改该特定实体时有效。

运行到演员表部分,我没有遵循从上下文中获取值需要做什么。他们正在定义 TEntity 但它的定义中没有任何内容。

您的问题似乎是 - 什么是 TEntity?

TEntity 是通用的。来自评论https://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx#csharp_generics_topic2

中提供的link

查看代码块

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}

T 正在指定通用。您可以插入 class - 就像您在实例化 Stack 时拥有 ProductInformation 的插件一样。例如-

var stk = new Stack<ProductInformation>();

我在其他答案的帮助下设法解决了我的问题,但是我发布了我的解决方案,因为它适用于使用 EF。

public static void PublishTable<TEntity>()
        {
            var targetEntity = typeof(TEntity).Name;
            var model = JsonConvert.DeserializeObject<Models.FullDataSetModel>(DataAccess.GetEnvironmentJson((int)Environments.Production));
            using (var db = new LoginPageContentEntities())
            {
                var deployEntry = db.Deployment.Find((int)Environments.Production);
                deployEntry.DateUpdated = DateTime.Now;
                deployEntry.GetType().GetProperty(targetEntity).SetValue(deployEntry, false);
                model.GetType().GetProperty(targetEntity).SetValue(model, ((IEnumerable<TEntity>)(typeof(LoginPageContentEntities).GetProperty(targetEntity).GetValue(db, null))).ToList());
                deployEntry.JsonCache = JsonConvert.SerializeObject(model);
                db.SaveChanges();
            }
        }