2017-02-25 18 views
0

在實體框架6接合多個表之後獲得選定值I有三個表(簡化的示例中此問題):使用的EntityFramework數據庫優先方法產生使用lambda

Database diagram

模型。

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 -

「,請確保你沒有一個無限循環或無窮遞歸

有什麼根本或者我的查詢不正確?

+1

我認爲EF中的模型生成存在根本性錯誤。通常情況下,如果在表中僅有兩列作爲具有複合主鍵的外鍵的表中存在多對多關係,則該關係不會在設計器中顯示。模型類將具有每個關係模型的導航集合屬性。所以我相信你的設計師* OwnerDogMapper *不應該在edmx中。 http://stackoverflow.com/a/35527376/1433093 –

+0

@KundanSinghChouhan - 感謝您的職位。 OwnerDogMapper在edmx中。我可以編寫連接查詢,並且IDE也可以讀取它。 – sandiejat

回答

0

我後來發現了這個問題,我改變了我的WebAPIconfig中的configFormatter。cs文件:

config.Formatters.Remove(config.Formatters.XmlFormatter); 

一旦我刪除它,LINQ查詢按預期工作。我希望它可以在未來幫助別人!