如何创建包含查询模型列表的模型?

时间:2015-09-28 11:44:04

标签: c# sql-server

我正在尝试创建一个包含实体列表的实体。这是我的代码:

internal IEnumerable<Project> GetProjects(int customerId)
{
    string query = @"SELECT * 
                     FROM Project
                     INNER JOIN MediaAsset ON Project.CustomerId = MediaAsset.CustomerId
                     WHERE MediaAsset.CustomerId = @CustomerID";

    List<Project> projects = new List<Project>();

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString))
    {
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            connection.Open();
            command.Parameters.AddWithValue("@CustomerID", customerId);

            using (varreader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    projects.Add(new Project
                    {
                        Assets = new List<MediaAsset>()//<--list of assets nested in Project
                        {
                              //right here.. how do i create the list of MediaAssets?
                        },
                        CustomerId = (int)reader["CustomerId"],
                        ProjectId = (int)reader["ProjectId"],
                        ProjectName = (string)reader["ProjectName"],
                        UserID = (int)reader["UserId"]
                    });
                }
            }
        }
    }

    return projects;
}

无论如何以这种方式完成它?我也一直在研究Linq-to-SQL,但我已经有很多方法,并且我希望保持代码一致。

1 个答案:

答案 0 :(得分:2)

考虑使用Dapper。您仍将使用SQL语句,但您将获得从接收的数据到实体对象的自动转换。