如何将带有 entity framework 的外键对象放入自定义对象中?

How to get foreign key objects with entity framework into a custom object?

我正在尝试使用 entity framework 5.0.

从数据库中创建一个 select

我有一个名为 Persons 的 table 被 PersonsImages 引用,所以基本上来自 Persons 的一条记录可以有很多 PersonsImages.

我做了一个 select 语句来给出人物,但我还想将人物图像作为 List<PersonsImages> 获取,并将它们放在自定义对象中。

这是我目前的代码:

var person = new Persons();

using (var context = new PersonEntities())
{
    person = context.Persons.Where(x => x.personId == 555)
                            .Select(xxx => new Persons
                            {
                                personName = xxx.personName,
                                personLastName = xxx.personLastName,
                                PersonImages = xxx.PersonsImages // there's an error here
                            })
                            .FirstOrDefault();
}

PersonsPersonsImages 类 看起来像这样(它们是 entity framework 生成的副本):

public partial class Persons
{
        public Persons()
        {
            this.PersonsImages = new HashSet<PersonsImages>();
        }

        public string personName { get; set; }
        public string personLastName { get; set; }
        public virtual ICollection<PersonsImages> PersonsImages { get; set; }
}

public partial class PersonsImages
{
        public string imageName { get; set; }
        public byte[] image { get; set; }
        public virtual Persons Persons { get; set; }
}

我知道我可以用第二个 select 和 "manually" 找到它们,但难道不能像 entity framework 通常那样一次完成吗?

假设您的错误是 "can't construct an object in a LINQ to Entities query" - 投射到匿名类型,调用 ToArray() 方法枚举结果,然后投射到 Persons 的新实例:

person = context.Persons.Where(x => x.personId == 555)
                        .Select(xxx => new
                        {
                            personName = xxx.personName,
                            personLastName = xxx.personLastName,
                            PersonImages = xxx.PersonsImages
                        })
                        .ToArray() // data now local
                        .Select(xxx => new Persons
                        {
                            personName = xxx.personName,
                            personLastName = xxx.personLastName,
                            PersonImages = xxx.PersonsImages
                        })
                        .FirstOrDefault();