EF - LINQ to Entities

时间:2016-09-23 18:19:37

标签: c# entity-framework linq viewmodel

我试图用控制器列出一些食物。我将Repository模式与UnitOfWork一起用于另一个程序集中的数据,并在BaseApiController中引用它。 数据属性是我的UnitOfWork实例。

var result = Data.Food
            .FindAll()
            .Select(FoodItemViewModel.Create);

return result;

这是我的ViewModel:

public static Expression<Func<FoodItem, FoodItemViewModel>> Create
    {
        get
        {
            return fi => new FoodItemViewModel
            {
                Id = fi.Id,
                Description = fi.Description,
                DiaryEntries = fi.DiaryEntries
                .Select(s => new DiaryEntityViewModel()
                {
                    Id = s.Id,
                    Quantity = s.Quantity
                }
            };
        }
    }

但我得到的只是:

  

&#34;指定的类型成员&#39; DiaryEntries&#39; LINQ不支持   实体。仅初始化程序,实体成员和实体导航   支持属性。&#34;

ViewModel中的My DiaryEntries成员是

IEnumerable<DiaryEntityViewModel>

我的数据实例中的DiaryEntries成员是

IRepository<DiaryEntry>

和DiaryEntry是我的模型类

这是我的FoodItem模型类:

public class FoodItem
    {
        private IEnumerable<Measure> measures;
        private IEnumerable<DiaryEntry> diaryEntries;

        public FoodItem()
        {
            this.measures = new HashSet<Measure>();
            this.diaryEntries = new HashSet<DiaryEntry>();
        }

        public int Id { get; set; }

        public string Description { get; set; }

        public virtual IEnumerable<DiaryEntry> DiaryEntries
        {
            get
            {
                return this.diaryEntries;
            }
            set
            {
                this.diaryEntries = value;
            }
        }

        public virtual IEnumerable<Measure> Measures
        {
            get
            {
                return this.measures;
            }
            set
            {
                this.measures = value;
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

将您FoodItem课程更改为以下课程, IEnumerable<T>不支持导航集类型

public class FoodItem
{
    public FoodItem()
    {
        this.Measures = new HashSet<Measure>();
        this.DiaryEntries = new HashSet<DiaryEntry>();
    }

    public int Id { get; set; }

    public string Description { get; set; }

    public virtual ICollection<DiaryEntry> DiaryEntries
    {
        get;
        set;
    }

    public virtual ICollection<Measure> Measures
    {
        get;
        set;
    }
}