c# - EF - LINQ to Entities 不支持

标签 c# entity-framework linq viewmodel

我正在尝试使用 Controller 列出一些食品。我将存储库模式与 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
                }
            };
        }
    }

但我得到的只是:

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

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

最佳答案

改变你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;
    }
}

关于c# - EF - LINQ to Entities 不支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39667220/

相关文章:

c# - Name For 在编辑器模板中遍历集合时生成不正确的名称

c# - 在 C# 中模拟 StreamReader 以进行单元测试

entity-framework - Entity Framework HierarchyId 解决方法

c# - 在组连接 linq 查询中将字符串转换为十进制

c# - 进程无法访问文件异常

c# - 登录网站并检索数据

c# - DbMigrator - 详细的代码优先迁移

jquery - 单击按钮多次加载部分 View

linq - 组合 3 个序列

c# - EF 一对多 where 条件