当前位置: 移动技术网 > IT编程>开发语言>.net > MySQL通过实例化对象参数查询数据

MySQL通过实例化对象参数查询数据

2018年10月14日  | 移动技术网IT编程  | 我要评论

广州女装批发市场,ca4101,芙蓉颜色txt下载

public static string querybyentity<t>(t t) where t : new()
{
    string resultstr = string.empty;
    mysqldatareader reader = null;
    try
    {
        type type = typeof(t);
        propertyinfo[] properties = type.getproperties();
        string select = string.format("select * from {0} {1}", type.name, "{0}");
        string where = string.empty;
        foreach (propertyinfo property in properties)
        {
            var value = t.getpropertyvalue<t>(property);
            if (value != null && !value.equals(property.getdefaultvalue()))
            {
                if (string.isnullorempty(where))
                {
                    where = string.format(" where {0}='{1}' ", property.name, value);
                }
                else
                {
                    where = string.format(" {0} and {1} = '{2}' ", where, property.name, value);
                }
            }
        }
        select = string.format(select, where);

        mysqlconnection connection = openconnection();
        if (connection == null)
            return resultstr;
        mysqlcommand _sqlcom = new mysqlcommand(select, connection);
        reader = _sqlcom.executereader();
        list<t> tlist = new list<t>();
        while (reader.read())
        {
            t t1 = new t();
            foreach (propertyinfo property in properties)
            {
                if (!string.isnullorempty(reader[property.name].tostring()))
                {
                    property.setmethod.invoke(t1, new object[] { reader[property.name] });
                }
            }
            tlist.add(t1);
        }
        resultstr = jsonconvert.serializeobject(tlist);
    }
    catch (exception ex)
    {
        logging.error(string.format("查询数据库失败,{0}", ex.message));
    }
    finally
    {
        if (reader != null)
        {
            reader.close();
            reader.dispose();
        }
    }
    return resultstr;
}

internal static class objectextend
{
    public static object getpropertyvalue<t>(this object obj, propertyinfo property)
    {
        type type = typeof(t);
        propertyinfo propertyinfo = type.getproperty(property.name);
        if (propertyinfo != null)
        {
            return propertyinfo.getmethod.invoke(obj, null);
        }
        return null;
    }

    public static object getdefaultvalue(this propertyinfo property)
    {
        return property.propertytype.isvaluetype ? activator.createinstance(property.propertytype) : null;
    }
}

通过实例化参数,对属性赋值,将对象作为参数传入,反射获取对象名称,列名,列值。要求对象名与表名一致,属性与列名一致。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网