【发布时间】:2015-10-28 16:35:07
【问题描述】:
我正在尝试使用 entity framework 5.0 从数据库中进行选择。
我有一个名为Persons 的表被PersonsImages 引用,所以基本上来自Persons 的一条记录可以有很多PersonsImages。
我已经创建了一个 select 语句来提供 Persons,但我也想将 PersonsImages 获取为 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();
}
Persons 和 PersonsImages 类看起来像这样(它们是实体框架生成的类的副本):
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; }
}
我知道我可以进行第二次选择并“手动”找到它们,但不能像 entity framework 通常那样一次性完成吗?
【问题讨论】:
-
您收到的错误信息是什么?您是否忘记将
personId属性放入问题中的Persons类?你有两个Persons类还是同一个类? -
既然投影到同一个类,何不试试 context.Persons.Include(p => p.PersonsImages).FirstOrDefault(x => x.PersonId == 555);跨度>
-
@YacoubMassad 例外是:
Cannot implicitly convert type 'System.Collections.Generic.ICollection<DataModel.PersonsImages>' to 'System.Collections.Generic.ICollection<MyModelClasses.PersonsImages>'. An explicit conversion exists (are you missing a cast?) -
@YacoubMassad 是的,我创建了一个本地
Persons类,这样我就可以在 DbContext 被释放时存储结果。 -
@SteveGreene 在这种情况下这对我没有帮助。
标签: c# entity-framework lambda entity-framework-5