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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With