Is there a ApplyPropertyChanges with a datacontext

2019-05-10 05:43发布

I have seen an example using the entiyt framework and it sued the ApplyPropertyChanges method to update an entity. Is there an equivilent method in plain old Linq-To-SQL?

My applicaiton is an asp.net MVC app and when I run my Edit action I want to just call sometihng like:

originalObject = GetObject(id);
DataContext.ApplyPropertyChanges(originalObject, updatedObject);
DataContext.SubmitChanges();

2条回答
▲ chillily
2楼-- · 2019-05-10 06:03

This method should do what you require:

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;
}
查看更多
趁早两清
3楼-- · 2019-05-10 06:06
var theObject = (from table in dataContext.TheTable
                 where table.Id == theId
                 select table).Single();

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

You can try to use the Attach method but it is buggy. Please see this link as a reference: LINQ to SQL Update

查看更多
登录 后发表回答