EntityObject上的Convert.ChangeType()

时间:2011-03-02 10:16:39

标签: mysql entity-framework entityobject

我正在使用.Net Connector 6.3.6开发MySQL并在VS 2010上创建实体模型。我打算编写一个将EntityObject添加到其对应表的泛型方法。以下是它的外观:

    public void AddToTable(ObjectContext dataContext, string tableName, EntityObject tableObj)
    {
                try
                {                        
                    Type type = dataContext.GetType();
                    string methodName = "AddTo" + tableName;
                    MethodInfo methodInfo = type.GetMethod(methodName);
                    PropertyInfo propInfo = dataContext.GetType().GetProperty(tableName);
                    Object[] parameters = new Object[] { Convert.ChangeType(tableObj, propInfo.PropertyType) };
                    methodInfo.Invoke(dataContext, parameters);
                }
                catch (Exception e)
                {

                  edit://gonna handle it appropriately here!
                }  
     }

ObjectContext将是实际的ObjectContext类。 但是当我在EntityObject上使用Covert.ChangeType()时,我正在异常说“对象必须实现IConvertible”。 如何克服这个问题? 编辑:仅供参考,我的主要目的是编写一个尽可能通用的方法,以便不需要转换为特定的表类型。

谢谢, 警报器

2 个答案:

答案 0 :(得分:2)

你正在重新发明轮子。

 public void AddToTable<TEntity>(ObjectContext dataContext, TEntity tableObj)
 {
     dataContext.CreateObjectSet<TEntity>().AddObject(tableObj);
 }

请不要吃异常。

答案 1 :(得分:0)

遵循以下通用存储库模式: [链接] http://www.codeproject.com/Articles/37155/Implementing-Repository-Pattern-With-Entity-Framew [link]它非常直观,符合我的要求:)

相关问题