从字典到列表获取数据

时间:2014-06-13 18:09:03

标签: c# asp.net-mvc-4

我在C#项目中有这些类

public class Category
        {
            [Key]
            public int CategoryId { get; set; }
            public string CategoryName { get; set; }

            public virtual ICollection<Subcategory> Subcategories { get; set; }
        }

public class Subcategory
    {
        [Key]
        public int SubCategoryId { get; set; }
        public string SubCategoryName { get; set; }
        public int CategoryId { get; set; }

        public virtual Category Category { get; set; }
        public virtual ICollection<Offer> Offers { get; set; }
    }

public class Offer
    {
        [Key]
        public int OfferId { get; set; }
        public string Title { get; set; }
        public virtual ICollection<Subcategory> SubCategory { get; set; }
    }

我在MVC项目中有这个课程

public class OfferViewModel
    {
        public int OfferId { get; set; }
        public string Title { get; set; }
        public Dictionary<string, List<SubCategoryViewModel>> Categories { get; set; }

    }

优惠可以包含多个子类别。所以我想添加到我的数据库中,提供和子类别。

public static bool GetModel(int UserId, OfferViewModel offerViewModel)
        {
            Offer offer = new Offer();
            offer.UserId = UserId;
            offer.Title = offerViewModel.Title;
for(int i=0;i<offerViewModel.Categories.Keys.Count;i++)
            {
                for (int j = 0; j < offerViewModel.Categories[offerViewModel.Categories.Keys.ElementAt(i)].Count; j++)
                { 
                    offer.Subcategory.Add(
                        new Subcategory{
                            SubCategoryId = offerViewModel.Categories[offerViewModel.Categories.Keys.ElementAt(i)][j].Id
                        }
                    );
                }
            }
}

我得到第二个FOR

的NULL

0 个答案:

没有答案