如何将模型类扩展到另一个模型?

时间:2014-07-10 13:41:28

标签: c# asp.net-mvc class

我正在尝试将一个类扩展到另一个将它们作为列表收集的类。

模型:

public class Brand
    {
        public int BrandId { get; set; }
        public string Name { get; set; }
        public string Guid { get; set; }
        public float Rating { get; set; }
        public string Industry { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Postal { get; set; }
        public string CountryCode { get; set; }

        public virtual Snapshot Snapshot { get; set; }
    }
public class Snapshot
{
        public int ID { get; set; }
        public string Guid { get; set; }
        public int CompanyID { get; set; }
        public string CompanyName { get; set; }
        public string Email { get; set; }
        public DateTime DateTimeSent { get; set; }
        public string Subject { get; set; }
        public string Html { get; set; }
        public string Image { get; set; }
        public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
    {
        public Brand Brand { get; set; }
        public List<Snapshot> SnapshotItems { get; set; }

    }

控制器:

public ActionResult Index(string brandGuid)
    {
        BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
        Brand brand = GetBrand(brandGuid);
        viewModel.Brand = brand;
        List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
        viewModel.SnapshotItems = snapshot;

        List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
        viewModelList.Add(viewModel);

        return View(viewModelList.AsEnumerable());
    }

private Brand GetBrand(string brandGuid)
{
    Brand brand = new Brand();
    string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
    MySqlConnection dbConn = new MySqlConnection(dbConnString);
    dbConn.Open();
    MySqlCommand dbCmd = new MySqlCommand();
    dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
    dbCmd.Connection = dbConn;
    MySqlDataReader dbResult = dbCmd.ExecuteReader();
    if (dbResult.Read())
    {
        brand.Guid = dbResult["brand_guid"].ToString();
        brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
        brand.Industry = dbResult["industry_name"].ToString();
    }
    dbResult.Close();
    dbConn.Close();

    return brand;
}

private List<Snapshot> GetBrandSnapshots(int brandId)
{
    string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
    MySqlConnection dbConn = new MySqlConnection(dbConnString);
    dbConn.Open();
    MySqlCommand dbCmd = new MySqlCommand();
    dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
    dbCmd.Connection = dbConn;
    MySqlDataReader dbResult = dbCmd.ExecuteReader();
    List<Snapshot> snapshots = new List<Snapshot>();
    while (dbResult.Read())
    {
        snapshots.Add(new Snapshot
        {
            SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
            Subject = dbResult["subject"].ToString(),
            DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
            Image = dbResult["image"].ToString(),
            Email = dbResult["email"].ToString(),
            ContentType = dbResult["content_type"].ToString(),
            Type = dbResult["type"].ToString()
        });
    }
    dbResult.Close();
    dbConn.Close();

    return snapshots;
}

编辑 固定

问题是VIEW没有将ViewModel引用为IENumerable&lt;&gt;。捂脸。

@model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
@{
    ViewBag.Title = "Index";
}
@foreach(var item in Model)
{
    @item.Brand.Guid;
    for(int i = 0; i< @item.SnapshotItems.Count; i++)
    {
        @item.SnapshotItems[i].Subject<br/>
    }
}

解决了这个问题。

感谢两位专家的见解......我接受了这两个建议并找到了解决方案。

2 个答案:

答案 0 :(得分:2)

你做错了,这是一个清单。

你不能这样添加元素。通过调用Add()

创建对象并在列表中添加该对象

这样做是为了在其中添加项目:

List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
    while (dbResult.Read())
    {
        BrandEmailList brandSnapshots = new  BrandEmailList (); // create an object
        brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
        brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
        brandSnapshots.DateTimeSent = dbResult["date_sent"];
        brandSnapshots.Subject = dbResult["subject"].ToString();
        brandSnapshots.Image = dbResult["image"];

       brandSnapshotsList.Add(brandSnapshots); // add it in list
    }

修改 列表是一个通用的东西,你不需要为它创建一个类。你可以实例化一个列表并在其中添加项目。

为什么你这样做只是这样做:

List<Snapshot> brandSnapshotsList = new List<Snapshot>();
        while (dbResult.Read())
        {
            Snapshot brandSnapshots = new  Snapshot(); // create an object
            brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
            brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
            brandSnapshots.DateTimeSent = dbResult["date_sent"];
            brandSnapshots.Subject = dbResult["subject"].ToString();
            brandSnapshots.Image = dbResult["image"];

           brandSnapshotsList.Add(brandSnapshots); // add it in list
        }

答案 1 :(得分:1)

以Ehsan Sajjad所做的为基础,看public IEnumerator<Snapshot> BrandEmails,我相信你看起来更像是这样:

public class Snapshot
{
    public int ID { get; set; }
    public string Guid { get; set; }
    // ...
}

public class BrandEmailList : List<Snapshot>
{
}

您甚至无需为品牌电子邮件列表创建新类型,您可以直接使用List<Snapshot>

public ViewResult Whatever() {
    var brand = GetBrand(brandName);
    var brandSnapshots = GetBrandSnapshots();

    return View(brand, brandSnapshots);
}

private Brand GetBrand(string brandName)
{
    try 
    {
        var brand = new Brand();
        brand.Name = brandName;
        // database stuffs ...
        return brand;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private List<Snapshot> GetBrandSnapshots()
{
    // ...
    // DB stuffs -- that *really* should not be in the controller anyways.
    // ...

    var snapshots = new List<BrandEmailList>();
    while (dbResult.Read())
    {
        // object initializer syntax
        snapshots.Add(new Snapshot {
            ID = Convert.ToInt32(dbResult["snapshot_id"]),
        Guid = dbResult["snapshot_guid"].ToString(),
        DateTimeSent = dbResult["date_sent"],
        Subject = dbResult["subject"].ToString(),
        Image = dbResult["image"],
        });     
    }
    return snapshots
}

作为旁注,将数据库访问混合到控制器方法中可能是一个坏主意。它不一定是,但它可以。通常,从数据库获取数据发生在与服务MVC结果不同的“级别”。 MVC控制器没有与数据库通信的“目的”,可以/应该将工作委托给专用类型。比较SOLID principles单一责任原则部分。