記錄一個EF連接查詢的異常:the entity or complex type 'x' cannot be constructed in a linq to entities query


問題解決連接:https://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query

 

鏈接是外文,我來翻譯一下,意思是相通的,主要是記錄一下供以后自己參考

 

問題描述:  product這個類是EF跟數據庫實體關聯的類,然后寫了如下一個查詢方法

 

public IQueryable<Product> GetProducts(int categoryID)
{
    return from p in db.Products
           where p.CategoryID== categoryID
           select new Product { Name = p.Name};
}

當需要用到這個方法查詢結果的時候,就像這樣:

var products = productRepository.GetProducts(1).Tolist();

就會拋出異常:

"The entity or complex type Shop.Product cannot be constructed in a LINQ to Entities query"

 

但是如果把方法改成下面這樣就沒有問題:

public IQueryable<Product> GetProducts(int categoryID)
{
    return from p in db.Products
           where p.CategoryID== categoryID
           select p;
}

這是為什么呢?可是我需要連接兩張表,並且需要兩張表的信息呢?

答案是,你用一個簡單的類,什么是簡單類呢?就是非“EF跟數據庫實體關聯的類”,就可以啦,然后把你想要的數據賦值進去就ok。

比如這樣,新建一個類叫SimpleProduct:

public class SimpleProduct {
        public string Name { get; set; }
    }

 

然后把方法改成:

public IQueryable<Product> GetProducts(int categoryID)
{
    return from p in db.Products
           where p.CategoryID== categoryID
           select new SimpleProduct { Name = p.Name};
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM