2010-09-20 41 views
0

我有一個很奇怪的問題。我遵循了一個MVC教程。Linq GetTable < >返回空行

我有一個接口:

namespace DomainModel.Abstract 
{ 
    public interface IProductsRepository 
    { 
     IQueryable<Product> Products { get; } 
    } 
} 

存儲庫繼承接口:

namespace DomainModel.Concrete 
{ 
    public class SqlProductsRepository : IProductsRepository 
    { 
     private Table<Product> productsTable; 
     public SqlProductsRepository(string connectionString) 
     { 
      try 
      { 
       productsTable = (new DataContext(connectionString)).GetTable<Product>(); 
      } 
      catch (Exception ex) 
      { 
       System.Diagnostics.Trace.WriteLine(ex.Message); 
      } 
     } 
     public IQueryable<Product> Products 
     { 
      get { return productsTable; } 
     } 
    } 
} 

我的產品類看起來是這樣的:

namespace DomainModel.Entities 
{ 
    [Table(Name = "Products")] 
    public class Product 
    { 
     [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] 
     public int ProductID { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public string Category { get; set; }  
     public decimal Price { get; set; } 

    } 
} 

我的控制器看起來像這樣:

namespace WebUI.Controllers 
{ 
    public class ProductsController : Controller 
    { 

     private IProductsRepository productsRepository; 
     public ProductsController() 
     { 
      string connString = @"Data Source=INFO_KW-HZ7YX91;Initial Catalog=SportStore;Integrated Security=True"; 
      productsRepository = new SqlProductsRepository(connString); 

     } 
     public ViewResult List() 
     { 
      return View(productsRepository.Products.ToList()); 

     } 

    } 
} 

我的產品表有8行。當我運行網站時,它顯示8行,但它們都是空格和零。當我調試它時,我可以看到productsTable有8行,列名正確,但字符串數據爲空,整數數據爲零。

我做錯了什麼?

感謝

+0

如果你不保留對它的引用,你如何設法在你的DataContext實例上調用Dispose?你正在將DataContext放置在每個請求的末尾,因此它的數據庫連接可以返回到連接池,對吧?留下像垃圾回收器打開的數據庫連接之類的東西從來不是一個好主意...... – 2010-09-20 18:23:29

回答

0

它已經相當一段時間,因爲我最後一次做自定義屬性這樣,但我猜你需要把[Column]你需要堅持的所有屬性。例如:

[Column] 
    public string Name { get; set; } 
    [Column] 
    public string Description { get; set; } 
    [Column] 
    public string Category { get; set; }  
    [Column] 
    public decimal Price { get; set; } 

假設您的SQL表字段名稱相應地匹配屬性名稱。

+0

糟糕,我忘了[Column]屬性。非常感謝你 – MsBugKiller 2010-09-20 18:48:40

0

您沒有將[Column]屬性添加到您的任何列,而是您的PK。 LinqToSql非常重要,手工編寫這些類將充滿風險和(很可能)令人恐懼的異常。您應該使用sqlmetal.exe或您自己的生成器。

相關問題