2014-03-19 121 views
0

我剛剛在教程後開始了我的第一個MVC應用程序。在我看來,我的代碼正好與教師匹配,但是出現錯誤:MVC實體框架 - 連接到數據庫

'System.Data.SqlClient.SqlException:無效的對象名稱'dbo.Employees'。' '[SqlException(0x80131904):無效的對象名稱'dbo.Employees'。]'

我的數據庫被稱爲'Sample',web配置反映了這一點。

任何人都可以看到我明顯的錯誤嗎?

感謝

僱員模型

namespace MvcApplication2.Models 
{ 
public class Employee 
{ 
    public int EmployeeId { get; set; } 
    public string Name { get; set; } 
    public string Gender { get; set; } 
    public string City { get; set; }  

} 
} 

僱員控制器

namespace MvcApplication2.Controllers 
{ 
public class EmployeeController : Controller 
{ 


    public ActionResult Details(int id) 
    { 
     EmployeeContext employeeContext = new EmployeeContext(); 
     Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id); 
     return View(employee); 
    } 

} 
} 

EmployeeContext.cs模型

namespace MvcApplication2.Models 
{ 
[Table("tblEmployee")] 
public class EmployeeContext : DbContext 
{ 
    public DbSet<Employee> Employees { get; set; } 
} 
} 

WebConfig

<connectionStrings> 
<add name="EmployeeContext" connectionString="Data Source={servername};Initial Catalog=Sample;Integrated Security=True" 
     providerName="System.Data.SqlClient" /> 
</connectionStrings> 

的Global.asax

Database.SetInitializer<MvcApplication2.Models.EmployeeContext>(null); 

回答

1

您對錯誤的類有您的數據註釋。您已將[Table("tblEmployee")]放在實體之上,而不是上下文。

它應該是你上面的Employee類,像這樣:

[Table("tblEmployee")] 
public class Employee 
{ 
    public int EmployeeId { get; set; } 
    public string Name { get; set; } 
    public string Gender { get; set; } 
    public string City { get; set; }  

} 
0

你工作的Code First?您可能需要設置正確的初始化程序,以便Entity Framework在不存在的情況下創建數據庫。

在您的Global.asax中的Application_Start設置此:

Database.SetInitializer<EmployeeContext >(new CreateDatabaseIfNotExists<EmployeeContext >()); 
+0

嗨。不,我已經創建了SQL服務器數據庫。我的Global.asax文件包含:'Database.SetInitializer (null);' – MJay

0

發現的問題。由於某種原因,它沒有使用我的數據註釋

[Table("tblEmployee")] 

刪除並重命名我的tbl似乎做了這項工作。任何人都知道它忽略了我的註釋?

+0

您需要將註釋放在Employee.cs類中,而不是EmployeeContext類 – Moeri

1

嘿,我也闖民宅同系列教程從http://csharp-video-tutorials.blogspot.com/2013/05/part-8-data-access-in-mvc-using-entity.html

添加

using System.ComponentModel.DataAnnotations; 

,然後用[關鍵]在表的主鍵屬性。即EmployeeId。

所以,你的代碼如下:

[Table("tblEmployee")] 
public class Employee 
{ 
    [Key] 
    public int EmployeeId { get; set; } 
    public string Name { get; set; } 
    public string Gender { get; set; } 
    public string City { get; set; }  

} 

不使用鑰匙,你會得到一個「模型生成過程中檢測到一個或多個驗證錯誤」 execption。

如果您需要更多幫助,我很樂意幫助您,因爲我也從同一系列中學習。 :)

快樂學習...!

相關問題