如何在LINQ中将对象的所有属性复制到另一个 [英] How to copy all properties of an object to another in LINQ

查看:116
本文介绍了如何在LINQ中将对象的所有属性复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个STUDENT表对象,其中有新值,并且我想用这些新值更新STUDENT表.我的代码如下所示(它正在将属性从STD复制到getdata起作用,但是)它没有更新数据库中STUDENT表中的值,为什么?先感谢您.

i have a STUDENT table object in which i have new values and i want to update the STUDENT table with these new values. my code is given bellow (which is working for copying properties from STD to getdata but) its not updating the values in STUDENT table in database why? thankyou in advance.

public void UpdateStudent(STUDENT STD)
    {
        context = new ERPDataContext();
        var getdata = context.STUDENTs.SingleOrDefault(obj=>obj.ID==STD.ID);
        getdata = STD;
        context.SubmitChanges();
    }

推荐答案

您可以在此处使用反射.不太确定它是否可以完全解决您的问题.另外,使用反射可能会造成太大的伤害,因此请检查性能.

You can use reflection here. Not very sure if it will solve your problem completely. Also using reflection can be an overkill so please check for performance.

我使用了一个虚拟类"A"来解释如何使用它.检查一下,让我知道它是否有效.

I have used a dummy class "A" to explain how you can use it. Check it out and let me know if it works.

    public class A 
    {
        public string aField { get; set; }
    }

代码是:

        A obj1 = new A();
        A obj2 = new A();

        obj1.aField = "aaa";

        var propInfo = obj1.GetType().GetProperties();
        foreach (var item in propInfo)
        {
            obj2.GetType().GetProperty(item.Name).SetValue(obj2, item.GetValue(obj1, null), null);
        }

当然,您需要添加名称空间:

Of course you need to add the namespace:

using System.Reflection;

希望这会有所帮助.

这篇关于如何在LINQ中将对象的所有属性复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆