在实体框架6接合多个表之后获得选定值I有三个表(简化的示例中此问题):使用的EntityFramework数据库优先方法产生使用lambda
模型。
OwnerModel
public partial class Owner
{
public Owner()
{
this.OwnerDogMapper= new HashSet<OwnerDogMapper>();
}
public string OwnerId { get; set; }
public string OwnerName { get; set; }
public virtual ICollection<OwnerDogMapper> OwnerDogMapper{ get; set; }
}
DogTable
public partial class Dog
{
public Dog()
{
this.OwnerDogMapper= new HashSet<OwnerDogMapper>();
}
public string DogId { get; set; }
public string DogName { get; set; }
public virtual ICollection<OwnerDogMapper> OwnerDogMapper{ get; set; }
}
和映射表:OwnerDogMapper
public partial class OwnerDogMapper
{
public string OwnerId { get; set; }
public string DogId { get; set; }
public virtual Owner Owner { get; set; }
public virtual Dog Dog { get; set; }
}
现在,我正试图加入这三个表,并在OwnerId传递时获取OwnerName和DogName。这里是我的查询:
var output = await (from o in db.Owner
join odm in db.OwnerDogMapper on o.OwnerId equals odm.OwnerId
join d in db.Dog on odm.DogId equals d.DogId
where o.OwnerId == '01'
select new { o.OwnerName, d.DogName }
).ToListAsync();
但它抛出一个异常:
例外: 的 'ObjectContent`1' 类型没有序列化 响应正文内容类型“application/xml进行;字符集= UTF-8' 。
类型 '<> f__AnonymousType2`2 [System.String,System.String]' 不能是 串行化。考虑使用DataContractAttribute 属性标记它,并使用DataMemberAttribute属性标记您想要序列化的所有成员。如果类型是集合,请考虑使用CollectionDataContractAttribute将其标记为 。有关其他支持的类型,请参阅Microsoft .NET Framework文档。
DataLayer将模型返回给使用AutoMapper完成DTO映射的BusinessLayer。 EF生成的模型中没有任何DataContracts。而且,到目前为止,在这个项目中,我已经远离了直接从DataLayer传递DTO。
如果我使用Lambda表达式,其类似于上Entity Framework Join 3 Tables
var output = await db.Owner
.Where(o => o.OwnerId == "01")
.Include(odm => odm.OwnerDogMapper.Select(d => d.Dog))
.ToListAsync();
然而提到的,在我的情况下,我没有[所有者]之间的任何关系,并[狗表。有了这个兰巴查询,它进入一个无限循环,我得到一个“StackOverflowException”:d -
“,请确保你没有一个无限循环或无穷递归
有什么根本或者我的查询不正确?
我认为EF中的模型生成存在根本性错误。通常情况下,如果在表中仅有两列作为具有复合主键的外键的表中存在多对多关系,则该关系不会在设计器中显示。模型类将具有每个关系模型的导航集合属性。所以我相信你的设计师* OwnerDogMapper *不应该在edmx中。 http://stackoverflow.com/a/35527376/1433093 –
@KundanSinghChouhan - 感谢您的职位。 OwnerDogMapper在edmx中。我可以编写连接查询,并且IDE也可以读取它。 – sandiejat