【问题标题】:Linq-to-SQL Moving DataObject from one DataClass to another, keeping structure. Howto?Linq-to-SQL 将 DataObject 从一个 DataClass 移动到另一个 DataClass,保持结构。如何?
【发布时间】:2012-01-04 15:06:27
【问题描述】:

一个问题不止一次出现在我面前。

我在 DataContext 中使用 Linq DataClass。在加载器运行完这个之后,它有时需要将一个对象移动到另一个具有相同结构的 DataClass。

所以 f.e. Products 和 ProductsHistory,每次在 Products 发生变化后,实际的 Product 都会被放入 ProductsHistory。

如何在不编写类似转换函数的情况下简化此操作:

private static ProductHistory convert(Product p)
    {
        ProductHistory ph = new ProductHistory();
        ph.Attr1 = p.Attr1;
        ph.Attr2 = p.Attr2;
        //...and hundreds like this on...
        return ph;
    }

我不想执行 DataContexts 支持的 SQL 查询。

任何提示都会很好,

提前致谢,

哈利

【问题讨论】:

    标签: c# asp.net sql linq linq-to-sql


    【解决方案1】:

    反射是自动完成的唯一方法

    通过反射,您必须探索源对象的所有属性。找到目标对象的相应属性。然后复制值

    //pseudo-code 
    //something like this 
    
    TargetInstance target = new TargetInstance();
    
    foreach(Property sourceProperty in sourceinstance)
    {
        if(target contains sourceProperty)
        {
            target[SourceProperty] = sourceInstance[SourceProperty];
        }    
    }
    

    看看this question和你的场景类似

    【讨论】:

    • 没有原生功能吗?这个问题不可能那么罕见(?)。
    • 不,没有原生功能
    • @Harry - 虽然不一定不常见,但请记住,这确实超出了 Linq 的范围。此外,至少还有另外两种通常可以解决此问题的方法 - SQL 触发器或 proc,或 B 类的自定义构造函数,该构造函数采用 A 类的实例并复制值。
    • 从 StackOverflow 中取出 this(注意,代码需要像给定的答案一样进行更正)并且它运行良好。谢谢大家!
    【解决方案2】:

    我会考虑将AutoMapper 用于此类事情...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 2014-04-22
      相关资源
      最近更新 更多