组合模型结果的最佳方法是什么

时间:2016-02-09 09:19:28

标签: c# entity-framework model-view-controller

我正在尝试将两个不同的模型组合到一个模型中,因此我可以将结果过滤为一个列表。

型号:

    public partial class OverviewItems
{
    // Videos and Images combined for overview
    [NotMapped]
    public List<dynamic> Item { get; set; }
}

我的控制器:

public ActionResult LoadItems(int skip = 0, int take = 4)
        {
            OverviewItems items = new OverviewItems();
            // get al the videos an images, order them by creaton date. Take onyly the latest videos/images combined.

        var images = db.Images.Where(i => i != null && i.Items != null && i.Items.Count() > 0).OrderByDescending(i => i.CreatedOn).Take(take).Skip(skip) as IEnumerable<object>;
        var videos = db.Videos.Where(v => v != null && !string.IsNullOrEmpty(v.Watch_id)).OrderByDescending(v => v.CreatedOn).Take(take).Skip(skip) as IEnumerable<object>;

        items.Item.Add(images);
        items.Item.Add(videos);

        // ViewBag.Items = images.Concat(videos);
        return PartialView("OverviewItems", items);
    }

视频和图片是带有项目的实体框架类。

    public partial class Videos : OverviewItems
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(250, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    public string Title { get; set; }

图像模型也是如此。但当然有不同的属性。

我也尝试了一个ViewBag,但这不起作用,因为视频和图像属于不同的类型,即使我将它们转换为动态。

我错过了哪一部分?是否有一个简单的解决方案来组合两个集合,以便我可以轻松地过滤/采取/跳过一个部分?

2 个答案:

答案 0 :(得分:2)

public abstract class OverviewItems
{
    public abstract string GetTitle();
}   

public class Videos : OverviewItems
{
    public string videoTitle { get; set; }
    public override string GetTitle()
    {
        return videoTitle;

    }
}

public class Images : OverviewItems
{
    public string imagesTitle { get; set; }
    public override string GetTitle()
    {
        return imagesTitle;

    }
}

 IList<OverviewItems> items = new List<OverviewItems>();

 var images = db.Images.Where(i => i != null && i.Items != null && i.Items.Count() > 0).OrderByDescending(i => i.CreatedOn).Take(take).Skip(skip).ToList();
 var videos = db.Videos.Where(v => v != null && !string.IsNullOrEmpty(v.Watch_id)).OrderByDescending(v => v.CreatedOn).Take(take).Skip(skip).ToList();

items.Add(images);
items.Add(videos);

var filtredItems = items.where(i=>i.GetTitle() == "SomeTitle");

答案 1 :(得分:0)

尝试“Concat”方法

var images = db.Images.Where(i => i != null && i.Items != null && i.Items.Count() > 0).OrderByDescending(i => i.CreatedOn).Take(take).Skip(skip) as IEnumerable<object>;

var videos = db.Videos.Where(v => v != null && !string.IsNullOrEmpty(v.Watch_id)).OrderByDescending(v => v.CreatedOn).Take(take).Skip(skip) as IEnumerable<object>;

var combined = images.Concat(videos);
items.Item.Add(combined);