【问题标题】:EF - not supported in LINQ to EntitiesEF - LINQ to Entities 不支持
【发布时间】:2016-09-23 18:19:37
【问题描述】:

我正在尝试使用控制器列出一些食品。我将 Repository 模式与 UnitOfWork 一起用于另一个程序集中的数据,并在 BaseApiController 中引用它。 Data 属性是我的 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
                }
            };
        }
    }

但我得到的只是:

“指定类型成员'DiaryEntries'在 LINQ to 中不受支持 实体。只有初始化器、实体成员和实体导航 支持属性。”

我在 ViewModel 中的 DiaryEntries 成员是

IEnumerable<DiaryEntityViewModel>

我在 Data 实例中的 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;
            }
        }
    }

【问题讨论】:

  • 你想在这里做什么?我认为您的问题可能是您将函数传递给数据库。在您的选择语句之前尝试.ToList()ing。
  • FoodItem 中的 DiaryEntries 是如何定义的?
  • IRepository&lt;DiaryEntry&gt; 是什么?该消息明确指出它应该是导航属性。
  • 日记条目是计算属性吗?
  • @IvanStoev IRepository 不在他的实体中,而是在他的 UnitOfWork 中。

标签: c# entity-framework linq viewmodel


【解决方案1】:

FoodItem 类更改为下面的类,IEnumerable&lt;T&gt; 不支持作为导航集合的类型

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

【讨论】:

  • 我使所有模型类都只具有导航属性,但仍然如此糟糕的响应。
  • 您将导航属性类型从 IEnumerable 更改为 ICollection?
  • 看来我得去睡觉或喝杯新咖啡了。愚蠢的错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多