2014-02-25 22 views
0

我正在做mvc練習並創建一個從數據庫中獲取數據的簡單頁面。在實踐中,我注意到一兩件事,我創建這個類:MVC4中的連接字符串

public class EmployeeContext : DbContext 
{ 
    public DbSet<Employee> Employees { get; set; } 
} 

在我的web.config首先,我添加了這個細節:

<connectionStrings> 
    <add name="con" connectionString="Server=XYZ;Database=mvc1;uid=sa;pwd=abcd;" providerName="System.Data.SqlClient"/> 
</connectionStrings> 

當我運行該應用中它給我的錯誤有無效的列名稱

但在那之後我互聯網上讀到它,我改變CONEmployeeContext,我創建,然後它的做工精細的類的名稱。像這樣:

<connectionStrings> 
    <add name="EmployeeContext" connectionString="Server=XYZ;Database=mvc1;uid=sa;pwd=abcd;" providerName="System.Data.SqlClient"/> 
</connectionStrings> 

現在我想知道現在我只創建一個簡單的類,我必須在連接字符串中給出類名稱。那麼這是否意味着我必須每次創建每個類的新連接字符串?

感謝

回答

0

對於樣品你有不同的類模型:

namespace MvcMusicStore.Models 
{ 
    public class Artist 
    { 
     public int ArtistId { get; set; } 
     public string Name { get; set; } 
    } 
} 

namespace MvcMusicStore.Models 
{ 
    public class Album 
    { 
     public int  AlbumId  { get; set; } 
     public int  GenreId  { get; set; } 
     public int  ArtistId { get; set; } 
     public string Title  { get; set; } 
     public decimal Price  { get; set; } 
     public string AlbumArtUrl { get; set; } 
     public Genre Genre  { get; set; } 
     public Artist Artist  { get; set; } 
    } 
} 
using System.Collections.Generic; 

namespace MvcMusicStore.Models 
{ 
    public partial class Genre 
    { 
     public int  GenreId  { get; set; } 
     public string Name  { get; set; } 
     public string Description { get; set; } 
     public List<Album> Albums { get; set; } 
    } 
} 

之後,你必須添加App_Data文件夾是在ASP.NET一個特殊的目錄,其已經具備了數據庫的正確的安全訪問權限訪問。從項目菜單中選擇添加ASP.NET文件夾,然後選擇App_Data。 在創建一個新的連接字符串:

<connectionStrings> 
    <add name="MusicStoreEntities" 
    connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf" 
    providerName="System.Data.SqlServerCe.4.0"/> 
    </connectionStrings> 
</configuration> 

,然後覆蓋不同DbSet您的應用程序類:使用System.Data.Entity的;

namespace MvcMusicStore.Models 
{ 
    public class MusicStoreEntities : DbContext 
    { 
     public DbSet<Album> Albums { get; set; } 
     public DbSet<Genre> Genres { get; set; } 
    } 
} 

如果你想創建一個新的類,你只需要把DbSet放到最後一個類中。 你可以在這裏找到所有的細節:http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-4

+0

感謝弗朗索瓦清除我的概念:)其真正有用 –

+0

不客氣:) –