MVC4中的Connectionstring

时间:2014-02-25 07:07:58

标签: asp.net-mvc-4 connection-string dbcontext

我正在进行mvc练习并创建一个简单的页面,用于从数据库中获取数据。在练习中,我注意到我创建了这个类的一件事:

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>

当我运行此应用程序时,它给出了错误有无效的列名称

但之后我在互联网上阅读了它,并将 con 更改为 EmployeeContext 我创建的类的名称,然后将其正常工作。像这样:

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

现在我想知道现在我只创建一个简单的类,我必须在连接字符串中给出类名。那么这是否意味着我必须为每个类创建每次新的连接字符串???

由于

1 个答案:

答案 0 :(得分: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

相关问题