Generic Edit in repository

只愿长相守 提交于 2019-12-24 12:06:16

问题


public T Update(T update) { }

Currently for this method I m implementing it like so..is there any other easy way around in Linq to SQL

public T Update (T update)
{
    var table = (IEnumerable<T>)(_table.AsQueryable());
    var store = (T)((from a in table.Where(
        a => a.GetType().GetPrimaryKey() == 
            update.GetType().GetPrimaryKey()) select a).Single());
    PropertyInfo[] properties = store.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        Object propertyValue = null;
        if (null != property.GetSetMethod())
        {
            PropertyInfo entityProperty =
                update.GetType().GetProperty(property.Name);
            if (entityProperty.PropertyType.BaseType ==
                Type.GetType("System.ValueType") ||
                entityProperty.PropertyType ==
                    Type.GetType("System.String"))
                propertyValue =
                    update.GetType().GetProperty(property.Name).GetValue(update, null);
                    if (null != propertyValue)
                        property.SetValue(store, propertyValue, null);
        }
    }
    _context.submitChanges
    return update   
}  

This works fine, however I was hoping if I could improve this code please...

_table is an ITable

来源:https://stackoverflow.com/questions/3923196/generic-edit-in-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!