2012-12-13 32 views
0

是否可以將連接的結果存儲在模型中的兩個/多個表上? 例如 說我有機型System.NotSupportedException:無法在LINQ to Entities查詢中構造實體或複雜類型「Project.Models.MyModel」

public class model1{ 
    public string studentID {get; set;} 
    public string Address [get; set;} 
} 

public class model2{ 
    public int ID {get; set;} 
    public string StudentName [get; set;} 
} 

public class model3{ 
    public string StudentName [get; set;} 
    public string Address [get; set;} 
} 

如果MODEL1和MODEL2從DATABSE得出的數據,我可以創建通過連接從模型1和模型2的結果model3?

編輯

所以,我不喜歡的東西

model3object = dbcontext.Model3.AsQueryable(); 
     model3object = from m1 in dbcontext.model1 
        let id = dbcontext.Model1.Select(x => m1.studentId).Cast<int>().FirstOrDefault() 
        join m2 in dbcontext.model2 
        on id equals m2.Id 
        select new Result 
        { 
         studentName = m2.studentName, 
         Address = m1.Adress, 
        }; 

,但我得到的錯誤

System.NotSupportedException: The entity or complex type 'ProjectName.Models.Model3' cannot be constructed in a LINQ to Entities query. 

我怎麼能解決這個問題嗎?

+0

模型不從數據庫中繪製數據,基本上Controller是這樣做的。您可以在控制器中運行連接查詢並使用結果數據填充Model3的對象,並將其傳遞給查看使用。 –

回答

0

我會使用兩種不同的模型。存儲來自數據庫的值和用於在mvc中顯示數據的視圖模型使用的模型。

在這個小例子看看:

var customerOrders = from o in myService.GetOrdersByCustomerId(id) 
        join p in myService.GetAllProducts() on o.ProductId equals p.Id 
        select new CustomerOrderViewModel 
        { 
         OrderId = o.Id, 
         ProductId = p.Id, 
         OrderDate = o.OrderDate, 
         ProductName = p.ProductName 
        }; 

你的代碼做同樣的你的模型1和模型2和這兩個模型映射到一個視圖模型。

+0

是的,我明白這一點,但我需要將其存儲在模型中,以便在我的視圖中進行訪問。我的觀點使用了幾種模型,這只是其中之一。這就是爲什麼我不能直接返回View(customerOrders)。 – jpo

+0

你的意思是你想要將多種類型的模型返回給視圖?我沒有在這裏跟蹤你。 @ MUG4N似乎有同樣的概念,我要回答。他假設你想將兩個對象映射(加入)到一個模型並將其呈現給視圖。你可以使用你想要的任何連接語句,並創建你想要的任何'連接'視圖模型。 –

+0

我的視圖有一個包含4個模型的「晚餐」模型類。我想在一個聯合查詢中加入其中的兩個,並將其與其他兩個模型一起傳遞給我。 – jpo

相關問題