简体   繁体   中英

EF - not supported in LINQ to Entities

I am trying to list some food items with a controller. I use Repository pattern with UnitOfWork for the data in another assembly and referenced it in a BaseApiController. The Data property is my UnitOfWork instance.

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

return result;

and here is my 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
                }
            };
        }
    }

But all I get is:

"The specified type member 'DiaryEntries' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

My DiaryEntries member in the ViewModel is

IEnumerable<DiaryEntityViewModel>

and my DiaryEntries member in the Data instance is

IRepository<DiaryEntry>

and DiaryEntry is my model class

and here is my FoodItem model class:

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;
            }
        }
    }

Change you FoodItem class to the one below, IEnumerable<T> is not supported as a type for a navigation collection :

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM