2011-04-21 202 views
5

我使用兩個DataContext對象來返回單獨的AsQueriable()數據集,然後使用linq連接兩個。但是,當我將該組合數據集傳遞給視圖時,數據構造完美地工作,我得到的錯誤'object'不包含'Name'的定義。'object'不包含'Name'的定義

在調試會話期間,我可以清楚地看到父級模型和foreach循環中的每個「項目」都具有可見/可訪問的所有數據和鍵。我很困惑。

許多其他問題匹配此問題的stackoverflow.com上的a不能解決我的問題,因此將欣賞一組全新的眼睛,並希望解決這個問題。

非常感謝! - 代碼時間:

的數據結構

 public ActionResult SplashImages() 
     { 
      var g = (from i in GetGallerySplash() join o in GetFestivals() on i.Festival equals o.ID orderby i.Rating descending select new {i.Photo, i.OwnedBy, i.Rating, o.Name }); 
      Response.ContentType = "text/xml"; 
      return View(g); 
     } 

     private IEnumerable<Gallery> GetGallerySplash() 
     { 
      GallerysDataContext gdc = new GallerysDataContext(); 
      return (from i in gdc.Galleries orderby i.Rating descending select i).Take(15).AsQueryable(); 
     } 

     private IEnumerable<Festival> GetFestivals() 
     { 
      FestivalsDataContext fdc = new FestivalsDataContext(); 
      return (from i in fdc.Festivals select i).AsQueryable(); 
     } 

VSExpress的錯誤畫面: Exception screenshot

在溶液中的任何指導,將不勝感激。謝謝!

Ç

+0

[訪問C#匿名類型對象](http://stackoverflow.com/questions/713521/accessing-c-sharp-anonymous-type-objects) – nawfal 2014-06-28 12:49:07

回答

4

我建議你創建一個模型來封裝兩個IEnumerable對象,例如

public class GalleryModel 
{ 
    public IEnumerable<Gallery> Galleries { get; set } 
    public IEnumerable<Festivals> Festivals { get; set; } 
} 

那麼強烈鍵入您的視圖以匹配模型

...Inherits="System.Web.Mvc.ViewPage<GalleryModel>" 

然後在你的模型,你可以輸入,安全是指每個對象,例如

<% foreach (var t in Model.Galleries) ... 
+0

感謝Tobias86,我正要完成這個確切的方法,因爲我看到了你的答案。你當然是完全正確的。我確實爲組合數據集製作了一個新模型,現在這個頁面運行得非常完美。非常感謝! – 2011-04-21 10:09:26

+1

很高興能有所幫助。我們必須處理類似的情況,所以我一直在你去過的地方:) – tobias86 2011-04-21 10:11:47

+1

我相信這被稱爲** MVVM **('Model View ViewModel')設計模式。基本上,您在模型和視圖之間添加了另一個圖層 - 視圖模型 - 使您可以更好地將模型封裝爲更易於查看的格式。許多使用MVVM模式的人在他們的項目中添加一個名爲'ViewModels'的文件夾,模擬Model,View和Controller文件夾的用法,並將其所有ViewModel類放入其中。 – 2011-09-15 10:09:03

-1

試着改變你的for循環:

<% foreach (dynamic t in Model) { %> 

採用var導致被推斷爲objectt類型。

+2

如果'Model'不是'IEnumerable 'i寧願去一個靜態類型的版本,並介紹一個poco ...'動態'基本上是純粹的反思! – 2011-04-21 09:54:00

+0

嗨馬修,我已經應用了這一變化,不幸的是我仍然得到同樣的錯誤。 – 2011-04-21 09:54:33

+0

問題是,匿名類型不會逃避操作方法的作用域,並且視圖只知道Model作爲類型對象。 – 2013-02-22 21:37:59

相關問題