Simplest way to populate class from query in C# [closed]

折月煮酒 提交于 2020-01-02 05:12:05

问题


I want to populate a class from a query. this is an example class:

private class TVChannelObject
{
    public string number { get; set; }
    public string title { get; set; }
    public string favoriteChannel { get; set; }
    public string description { get; set; }
    public string packageid { get; set; }
    public string format { get; set; }

}

How can I fill this class from an database query? Is there any way to do this automatically as far as table column names are identical to class attributes?


回答1:


As others have suggested, an ORM is the best way to go. You could, however, implement this functionality using reflection:

using System.Reflection;

void Main()
{
    var connectionString = "...";
    var records = new Query(connectionString).SqlQuery<TVChannel>("select top 10 * from TVChannel");
}

private class TVChannel
{
    public string number { get; set; }
    public string title { get; set; }
    public string favoriteChannel { get; set; }
    public string description { get; set; }
    public string packageid { get; set; }
    public string format { get; set; }
}

public class Query
{
    private readonly string _connectionString;

    public Query(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<T> SqlQuery<T>(string query)
    {
        var result = new List<T>();

        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = query;
                using (var reader = command.ExecuteReader())
                {
                    var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
                    var properties = typeof(T).GetProperties();

                    while (reader.Read())
                    {
                        var data = new object[reader.FieldCount];
                        reader.GetValues(data);

                        var instance = (T)Activator.CreateInstance(typeof(T));

                        for (var i = 0; i < data.Length; ++i)
                        {
                            if (data[i] == DBNull.Value)
                            {
                                data[i] = null;
                            }

                            var property = properties.SingleOrDefault(x => x.Name.Equals(columns[i], StringComparison.InvariantCultureIgnoreCase));

                            if (property != null)
                            {
                                property.SetValue(instance, Convert.ChangeType(data[i], property.PropertyType));
                            }
                        }
                        result.Add(instance);
                    }
                }
            }
        }
        return result;
    }
}



回答2:


You can use Linq to SQL with C#. With Linq, you can easily map your tables with C# classes and then query or populate them with a few lines of code.

Check out this link: Insert rows with Linq to SQL

EDIT:

The first thing you need to do is to map your class to your database table. Like this:

[Table(Name = "tvchannel")] // Here you put the name of the table in your database.
private class TVChannelObject
{
    Column(Name = "number", IsPrimaryKey = true)] // Here, number is the name of the column in the database and it is the primary key of the table.
    public string number { get; set; }

    [Column(Name = "title", CanBeNull = true)] // If the field is nullable, then you can set it on CanBeNull property.
    public string title { get; set; }

    [Column(Name = "channelFavorite", CanBeNull = true)] // Note that you can have a field in the table with a different name than the property in your class.
    public string favoriteChannel { get; set; }

    [Column(Name = "desc", CanBeNull = true)]
    public string description { get; set; }

    [Column(Name = "package", CanBeNull = false)]
    public string packageid { get; set; }

    [Column(Name = "format", CanBeNull = false)]
    public string format { get; set; }

}

After mapping your database with the corresponding fields for your table, you can now build a method in your class to insert a row:

public void InsertTvChannel()
{
    // DataContext takes a connection string. 
    string connString = "Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish" //example
    DataContext db = new DataContext(connString);

    // Create a new object tv channel to insert
    TVChannelObject channel = new TVChannelObject();
    channel.number = 1;
    channel.title = "Some title";
    channel.favoriteChannel = "some channel";
    channel.description = "some description";
    channel.packageid = "the package id";
    channel.format = "the format";

    // Now that you have the object for the new channel, let's insert it:
    db.TVChannelObjects.InsertOnSubmit(channel); //this just adds to a collection. It is a prepare to insert.

    // Submit the change to the database.
    try
    {
         db.SubmitChanges();
    }
    catch (Exception e)
    {
         Console.WriteLine(e);
        // If you face errors, you can handle it with some code here.
        // ...
        // Try again.
        db.SubmitChanges();
    }
}

This code should work, with just a few adjustments. Now you have an example to insert with a Linq mapping.




回答3:


Use ORM like entity framework. For your simplicity , follow this link

www.codeproject.com/Articles/739164/Entity-Framework-Tutorial-for-Beginners



来源:https://stackoverflow.com/questions/32693583/simplest-way-to-populate-class-from-query-in-c-sharp

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