0

我正在使用以下内容从数据库查询中创建对象:

public static T Query<T>(this MySqlConnection conn, string query) where T : new()
    {
        T obj = default(T);
        conn.Open();
        using (MySqlCommand command = new MySqlCommand(query, conn))
        {
            using (MySqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    obj = new T();

                    PropertyInfo[] propertyInfos;
                    propertyInfos = typeof(T).GetProperties();

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        var name = reader.GetName(i);

                        foreach (var item in propertyInfos)
                        {
                            if (item.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) && item.CanWrite)
                            {
                                item.SetValue(obj, reader[i], null);
                            }
                        }

                    }
                }
            }
        }
        conn.Dispose();

        return obj;
    }

我知道那里的图书馆和使用 linq 等。但我真正追求的是上面的有效反转。我想将它传递给一个对象并将其插入数据库但无法弄清楚:

我有以下但无法获取对象的值来构建插入查询:

public static T Insert<T>(this MySqlConnection conn) where T : new()
    {
        string query = "INSERT INTO " + typeof(T).Name;
        string fields = "(";
        string values = "(";

        T obj = default(T);
        conn.Open();
        using (MySqlCommand command = conn.CreateCommand())
        {
            obj = new T();

            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(T).GetProperties();

            command.CommandText = query;
            command.ExecuteNonQuery();
        }
        conn.Close();

        return obj;

    }

帮助表示赞赏。我只想要一个从传递的对象构建的插入查询。第一部分适用于以下类以从属性表中进行选择:

public class Property : ManagedObject
{
    private int id; //(most sites the property will have a unique ID)
    private string address;
    private string city;
    private string state;
    private string zipCode;
    private string propertyUrl;
    private string status; //Status of the Property (most have that option, and it either says “in contract” or “price reduced” (most sites will have this don’t worry about the one that don’t)
    private Propertytype type;

    private double price;
    private double squareFeet;

    private DateTime listDate; //(date it first appeared on the site or if one is given, that date)
    private DateTime yearBuilt;

    private List<PriceDrop> priceDrops;

    public Property()
    {
        priceDrops = new List<PriceDrop>();
    }

    public int ID
    {
        get { return this.id; }
        set
        {
            this.CheckPropertyChanged<int>
            ("ID", ref this.id, ref value);
        }
    }

    public string Address
    {
        get { return this.address; }
        set
        {
            this.CheckPropertyChanged<string>
            ("Address", ref this.address, ref value);
        }
    }

    public string City
    {
        get { return this.city; }
        set
        {
            this.CheckPropertyChanged<string>
            ("City", ref this.city, ref value);
        }
    }

    public string State
    {
        get { return this.state; }
        set
        {
            this.CheckPropertyChanged<string>
            ("State", ref this.state, ref value);
        }
    }

    public string ZipCode
    {   
        get { return this.zipCode; }
        set
        {
            this.CheckPropertyChanged<string>
            ("ZipCode", ref this.zipCode, ref value);
        }
    }

    public string PropertyUrl
    {   
        get { return this.propertyUrl; }
        set
        {
            this.CheckPropertyChanged<string>
            ("PropertyUrl", ref this.propertyUrl, ref value);
        }
    }

    public string Status
    {   
        get { return this.status; }
        set
        {
            this.CheckPropertyChanged<string>
            ("Status", ref this.status, ref value);
        }
    }

    public Propertytype Type
    {
        get { return this.type; }
        set
        {
            this.CheckPropertyChanged<Propertytype>
            ("Type", ref this.type, ref value);
        }

    }

    public double Price
    {
        get { return this.price; }
        set
        {
            this.CheckPropertyChanged<double>
            ("Price", ref this.price, ref value);
        }
    }

    public double SquareFeet
    {   
        get { return this.squareFeet; }
        set
        {
            this.CheckPropertyChanged<double>
            ("SquareFeet", ref this.squareFeet, ref value);
        }
    }

    public DateTime ListDate
    {
        get { return this.listDate; }
        set
        {
            this.CheckPropertyChanged<DateTime>
            ("ListDate", ref this.listDate, ref value);
        }
    }

    public DateTime YearBuilt
    {
        get { return this.yearBuilt; }
        set
        {   
            this.CheckPropertyChanged<DateTime>
            ("YearBuilt", ref this.yearBuilt, ref value);
        }
    }

    public List<PriceDrop> PriceDrops
    {
        get { return this.priceDrops; }
        set
        {
            this.CheckPropertyChanged<List<PriceDrop>>
            ("PriceDrops", ref this.priceDrops, ref value);
        }
    }

}

var query = ObjectFactory.Query<Property>(AppSettings.Instance.MySqlConn, "SELECT * FROM Property");

现在我只需要插入。

4

2 回答 2

0

我认为您正在寻找的是像Dapper-dot-net这样的 Micro ORM 。您可以使用 Microsoft 的 Entity Framework,但对于您的场景来说,它似乎相当繁重。我认为像 dapper 这样的 Micro ORM 是要走的路。

于 2012-12-18T13:12:57.130 回答
0

我最终在当前项目中回到了这个问题并整理了我想要做的事情,下面是用于 Sql 数据库连接并在表中插入共享相同名称和字段值的对象,所以我不必编写再次插入任何对象:

public static void Insert(this SqlConnection conn, object p)
        {
            string query = "INSERT INTO {0} ({1}) VALUES ({2})";
            conn.Open();

            using (SqlCommand command = conn.CreateCommand())
            {
                PropertyInfo[] propertyInfos;
                propertyInfos = p.GetType().GetProperties();

                var objF = String.Join(",", propertyInfos.Select(i => i.Name).ToArray());
                //var objV = String.Join(",", propertyInfos.Select(i => i.GetValue(p, null)).ToArray());

                var objV = "";
                string[] array = new string[p.GetType().GetProperties().Count()];
                foreach (PropertyInfo info in p.GetType().GetProperties())
                {
                    if (info.GetValue(p,null).GetType() == typeof(string))
                    {
                        objV += "'"+(string)info.GetValue(p, null) + "',";
                    }
                    else if (info.GetValue(p, null).GetType() == typeof(DateTime))
                    {
                        objV += "CAST('" + ((DateTime)info.GetValue(p, null)).ToString("yyyy-MM-dd hh:mm:ss")+ "' AS DATETIME),";
                    }
                    else if (info.GetValue(p, null).GetType() == typeof(bool))
                    {
                        objV += "'" + ((bool)info.GetValue(p, null) == true ? "1" : "0") +"',";
                    }
                    else
                    {
                        objV += "'" + (string)info.GetValue(p, null) + "',";
                    }
                }

                command.CommandText = string.Format(string.Format(query, p.GetType().Name, objF, objV.TrimEnd(new char[] { ',' })));
                command.ExecuteNonQuery();
            }
            conn.Close();

        }

下面是一个与调用表和对象一起使用的快速示例:

Business.Objects.Call c = new Business.Objects.Call();
            c.Number = "07889876774";
            c.StartTime = DateTime.Now;
            c.EndTime = DateTime.Now.AddHours(1);
            ObjectFactory.Insert(AppSettings.Instance.SqlConn, c);

怪胎布亚。

于 2013-02-10T20:17:28.227 回答