[MVC] model类中Virtual的作用

在学习MusicStore教程中,执行程序->查看唱片详细信息时,弹出以下异常:

 

代码如下:

Model层Album类结构为:

 

[csharp] view plaincopy
  1. public class Album  
  2.    {  
  3.        public int AlbumId { getset; }  
  4.        public int ArtistId { getset; }  
  5.        public int GenreId { getset; }  
  6.        public string Title { getset; }  
  7.        public decimal Price { getset; }  
  8.        public string AlbumArtUrl { getset; }  
  9.   
  10.        public Genre Genre { getset; }  
  11.        public Artist Artist { getset; }  
  12.    }  


Controller层显示该界面的方法为:

 

 

  1. public ActionResult Details(int id)  
  2.        {  
  3.            var album = storeDB.Albums.Find(id);  
  4.            return View(album);  
  5.        }  

因为异常显示Genre未实例化,所以开始的解决办法是在Details方法里,将

 

 

[csharp] view plaincopy
  1. var album = storeDB.Albums.Find(id);  


改为

 

 

[csharp] view plaincopy
  1. var album = storeDB.Albums.Include("Genre").Include("Artist").Single(item => item.AlbumId == id);  

后,界面显示正常。但是有个疑问——MusicStore教程中并没有这样写呀...

 

仔细对照代码后,教程中发现Album类关于Genre和Artist的定义中各多了Virtual修饰符,更改后原来的代码执行成功!

关于Virtual,教程中的原文如下:

While we’re there, we’ve also changed the Genre and Artist to virtual properties. This allows Entity Framework to lazy-load them as necessary.

理解为:使用了virtual的类或类集合的好处在于延时加载,只有在使用该数据时,EF再去自动执行数据加载操作。

 

最后Model层代码如下:

 

[csharp] view plaincopy
  1. public class Album  
  2.    {  
  3.        public int AlbumId { getset; }  
  4.        public int ArtistId { getset; }  
  5.        public int GenreId { getset; }  
  6.        public string Title { getset; }  
  7.        //[Required(ErrorMessage="Price is required!")]  
  8.        public decimal Price { getset; }  
  9.        public string AlbumArtUrl { getset; }  
  10.   
  11.        public virtual Genre Genre { getset; }  
  12.        public virtual Artist Artist { getset; }  
  13.    }  

 

Controller中的代码维持原来的不变.

posted @ 2013-08-04 13:10  邹邹  Views(298)  Comments(0)    收藏  举报