如何在C#中填充具有列表类型成员的对象 [英] How to Populate an object which has a member of list Type in C#

查看:103
本文介绍了如何在C#中填充具有列表类型成员的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有一个Genere类别,如下所示

Hello,

I have a Genere Class as below

public class Genre
    {
        public int GenreId { get; set; }
        public string Name { get; set; }
        public string Description {get; set;}
        public List<Album> Albums { get; set; }
    }



我正在尝试通过在DAL类中使用以下代码来填充流派对象:



I am trying to populate the Genre objet by using below code in my DAL class

public List<Genre> GetAlbumByGenreName(string genre)
{
    IList<Genre> genres = new List<Genre>();
    IList<Album> albums = new List<Album>();
    Database db = DatabaseFactory.CreateDatabase();
    DbConnection cn = db.CreateConnection();
    cn.Open();

    DbCommand cmd = cn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select g.GenreId,Name,Description, A.Title from Genre g Inner Join Album A on g.GenreId = a.GenreId Where g.Name = ''" + genre + "''";
    using (SqlDataReader dr = cmd.ExecuteReader() as SqlDataReader)
    {
        while (dr.Read())
        {
            genres.Add(new Genre
            {
                GenreId = dr.GetInt32(0),
                Name = dr.GetString(1),
                Description = dr.GetString(2)//,
                //Albums = dr.GetString(3)
            });
        }
    }
    return genres.ToList();
}



我的问题是如何填充流派类别的专辑成员.
在我的数据库中,一个流派可以有多个专辑,并且我必须使用企业库的数据访问应用程序数据块.

在此先谢谢您.



My Question is how i can populate the Albums member of Genre Class.
In my database one Genre can have multiple Albums and I have to Use Enterprise Library''s Data Access Application Data Block.

Thanks in Advance.

推荐答案

由于您获得了具有相同流派(和不同专辑)的多行,因此您必须填充所有行并跟踪已解析的流派.例如,在类型列表中找到该类型.如果类型已经存在,则只需向该对象添加一个新专辑,否则将一个新类型添加到列表中(当然,新闻阅读专辑也要添加).

通过genreid添加订单可以帮助您简化订单.然后,您只需要记住以前的流派.

问候
Piet
Since you get multiple rows with the same genre (and different albums), you must populate all the rows and keep track of the already parsed genres. For example find the genre in the genres list. When the genre already exists just add the a new album to this object otherwise add a new genre to the list (and of course the news read album).

Adding a order by genreid can help you to simplify it. Then you only have to remember the previous genreid.

Regards
Piet


这篇关于如何在C#中填充具有列表类型成员的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆