Is there a ApplyPropertyChanges method with datacontext?

I saw an example using the entiyt framework, and he applied the ApplyPropertyChanges method to update the object. Is there an equal method in plain old Linq-To-SQL?

My applicaiton is an asp.net MVC application, and when I run the "Edit" action, I just want to call sometihng, for example:

originalObject = GetObject(id);
DataContext.ApplyPropertyChanges(originalObject, updatedObject);
DataContext.SubmitChanges();
+3
source share
2 answers

This method should do what you need:

public static void Apply<T>(T originalValuesObj, T newValuesObj, params string[] ignore)
    where T : class
{
    // check for null arguments
    if (originalValuesObj == null || newValuesObj == null)
    {
        throw new ArgumentNullException(originalValuesObj == null ? "from" : "to");
    }

    // working variable(s)
    Type type = typeof(T);
    List<string> ignoreList = new List<string>(ignore ?? new string[] { });

    // iterate through each of the properties on the object
    foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
        // check whether we should be ignoring this property
        if (ignoreList.Contains(pi.Name))
        {
            continue;
        }

        // set the value in the original object
        object toValue = type.GetProperty(pi.Name).GetValue(newValuesObj, null);
        type.GetProperty(pi.Name).SetValue(originalValuesObj, toValue, null);
    }

    return;
}
+2
source
var theObject = (from table in dataContext.TheTable
                 where table.Id == theId
                 select table).Single();

theObject.Property = "New Value";
dataContext.SubmitChanges();

You can try using the Attach method, but it is buggy. See This Link as a Link: LINQ to SQL Update

+1
source

Source: https://habr.com/ru/post/1717926/


All Articles