2012-08-03 105 views
8

我使用「實體框架DbContext」的時刻,我有異常towars.dbo未找到。這很奇怪,因爲在我的網站上,我一直在問關於towar.dbo,但沒有towars.dbo你知道問題出在哪裏嗎?實體框架添加到我的.dbo

- InnerException {"Invalid object name 'dbo.Towars'."} System.Exception {System.Data.SqlClient.SqlException} 

我對Towar(在我的程序,當然不同的地方)的所有東西:

public class ProductController : Controller 
{ 
    // 
    // GET: /Product/ 
     public ITowarRepository repository; 

     public ProductController(ITowarRepository productRepository) 
     { 
     repository = productRepository; 
     } 

     public ViewResult List() 
     { 
      return View(repository.Towar); 
     } 

} 


public interface ITowarRepository 
    { 
     IQueryable<Towar> Towar { get; } 
    } 

public DbSet<Towar> Towar { get; set; } 

public class EFTowarRepository : ITowarRepository 
    { 
     public EFDbContext context = new EFDbContext(); 
     public IQueryable<Towar> Towar 
     { 
      get { return context.Towar; } 
     } 
    } 
public class Towar 
    { 
     [Key] 
     public int Id_tow { get; set; } 
     public string Nazwa { get; set; } 
     public string Opis { get; set; } 
     public decimal Cena { get; set; } 
     public int Id_kat { get; set; } 
    } 
+0

什麼是在你的數據庫表名?是否連接到正確的數據庫? – Shyju 2012-08-03 15:58:24

+0

連接數據庫是否正確 RPD 2012-08-03 16:00:34

回答

2

你可以告訴EF用流利的API重寫OnModelCreating方法在DBContext類這樣的映射表Towar

public class EFDbContext : DbContext 
{ 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Towar>().ToTable("Towar"); 
    } 
} 

現在EF會尋找Towar表,而不是Towars。如果你沒有創建這些表,還有一些其他問題。

+0

感謝您的幫助:)我不明白他們爲什麼在Visual Studio中創建這個愚蠢的東西,但我非常樂意爲您提供幫助。 – RPD 2012-08-03 16:14:33

+0

@RPD:不客氣。很高興我能幫到 – Shyju 2012-08-03 16:16:11

+0

需要打電話給基地? 'base.OnModelCreating(modelBuilder);' – 2017-07-05 14:45:48

4

EF代碼優先自動複數化表名。使用[Table]屬性的實體明確地映射到表名:

[Table("Towary")] 
public class Towary 
{ 
    // Whatever properties 
} 

看起來有一種方法來禁用多元化gobally也看到Entity Framework Code First naming conventions - back to plural table names?

+0

錯誤'名稱'不是有效的命名屬性參數。命名屬性參數必須是不是隻讀,靜態或常量的字段,或者是公共的而非靜態的讀寫屬性。 \t C:\ Users \ Rafal \ Desktop \ MVCksiązka\ moj projekt \ sklep \ SportsStore \ Entities \ Product.cs SportsStore.Domain – RPD 2012-08-03 16:04:40

+0

對不起,我讀了錯誤的文檔。它應該是'[Table(「Towary」)]'。 – 2012-08-03 16:07:08

+0

感謝您的時間和幫助 – RPD 2012-08-03 16:11:37

10

以下行添加到您的上下文:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
+0

謝謝,但現在正在正常工作 – RPD 2012-08-03 16:12:12

+3

這是最好的方式,因爲其他解決方案只是一次性修復。 – 2014-06-04 17:43:40

2
using System.Data.Entity.ModelConfiguration.Conventions; 

namespace MVCDemo.Models 

    { 
     public class EmployeeContext : DbContext 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
     } 
} 

爲了完整起見@ 42

+0

隨着你的回覆@Crismogram,我可以連接到遠程數據庫,沒有任何問題....偉大的答案... – 2017-09-18 17:42:03