Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy all properties of an object to another in LINQ

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();
    }
like image 690
Yogseh pathak Avatar asked Dec 05 '22 07:12

Yogseh pathak


2 Answers

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.

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; }
    }

And the code is:

        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;

Hope this helps.

like image 56
samar Avatar answered Jan 12 '23 19:01

samar


You have to update all properties manually:

var getdata = context.STUDENTs.SingleOrDefault(obj=>obj.ID==STD.ID);
getdata.Prop1 = STD.Prop1;
getdata.Prop2 = STD.Prop2;
context.SubmitChanges();

Otherwise, you're just replacing getdata reference, and do not change the object itself.

Or you can use following:

var getdata = context.STUDENTs.SingleOrDefault(obj=>obj.ID==STD.ID);
var entry = context.Entry(getdata);
entry.CurrentValues.SetValues(STD);
entry.State = EntityState.Modified;
context.SubmitChanges();
like image 42
MarcinJuraszek Avatar answered Jan 12 '23 20:01

MarcinJuraszek