MVC4无法连接到SQL Server 2008中的远程数据库 [英] MVC4 can't connect to SQL Server 2008 remote DB

查看:255
本文介绍了MVC4无法连接到SQL Server 2008中的远程数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了以前一些关于这个问题,但我不能解决我的问题。

我有连接简单的数据库MVC项目的问题。这是很难做到的,我使用VS2010,SQL Server 2008中(远程DB)。我有一个数据库已经建立,我想先用code。与实体框架。听起来很简单,我只要按照教程,但没有教程中,我采用了工作过。该教程使用旧的MVC和旧的实体框架。我有MVC4和EF 5

下面是我使用的步骤


  1. 创建新的MVC项目,并引用我看到实体框架


  2. 创建类,将对应于数据库尚未创建表


  3. 连接字符串添加到的web.config


  4. 添加额外的行的Global.asax 来避免错误实体5抛出了(从其他民族问题发现了这本)


  5. 与db和添加的DbContext控制器


  6. 运行项目,你能猜出一个问题,控制器称为视频发生


错误:


  

异常详细信息:System.Data.SqlClient.SqlException:无效的对象
  命名dbo.videos。


我不知道,这似乎MVC很多比Web表单更不稳定,因为我可以在web表单连接到同一数据库没有问题。

 <添加名称=videoDBContext
       的connectionString =数据源= XXXXXXX;初始目录= XX;坚持安全信息= TRUE;用户ID = XX;密码= XXX
       的providerName =System.Data.SqlClient的/>

类:

 公共类视频
{
    公众诠释ID {搞定;组; }
    公共字符串名称{搞定;组; }
    公众的DateTime RELEASEDATE {搞定;组; }
    公共字符串类型{搞定;组; }
    公共十进制价格{搞定;组; }
}

的DbContext:

 公共类videoDBContext:的DbContext
{
    公共DbSet<视频>视频{搞定;组; }
}

控制器动作

 公众的ActionResult指数()
    {
        返回查看(db.videos.ToList()); //
  异常详细信息:System.Data.SqlClient.SqlException:无效的对象名称dbo.videos。
    }


解决方案

您要连接到数据库的罚款。实际的DB模式和codefirst模型不同步,因此错误。

您要添加一个DbSet到的DbContext视频,但是你现有的数据库中不存在这样的表。除非你的数据库的初始化状态创建当它不存在的车型,这正是错误,我期望你得到。

另外,我看到定义或提及任何映射类,模型类映射到数据库表。

看看<一个href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application.这种进入接近尾声数据库intializers。另一种选择是简单地手动创建表。

所以,问题之一,没有数据库初始化(或pre定义的表)。问题二,从你什么显示任何映射类表和OnModelCreating,至少。这是完全可能的,你不使用流利的API来定义您的映射,而是只是使用在视频模式属性,但同样,你没有显示,所以我要告诉你的流利的方式。

编辑:

我已经更新了我从你的命名约定本地创建一个测试项目本code。这100%的工作。这些都是确切类我创建或反向工程。

 公共类videoDBContext:的DbContext
{
    静态videoDBContext()
    {
        Database.SetInitializer&LT; videoDBContext&GT;(NULL);
    }    公共videoDBContext()
        :基地(NAME = videoDBContext)
    {
    }    公共DbSet&lt;视频&GT;影片{搞定;组; }    保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        modelBuilder.Configurations.Add(新VideoMap());
    }
}

域类

 公共类视频
{
    公众诠释标识{搞定;组; }
    公共字符串描述{搞定;组; }
}

和映射类

 公共类VideoMap:EntityTypeConfiguration&lt;视频&GT;
{
    公共VideoMap()
    {
        // 首要的关键
        this.HasKey(T =&GT; t.Id);        //属性
        this.Property(T =&GT; t.Description)
            。是必须的()
            .HasMaxLength(50);        //表&安培;列映射
        this.ToTable(视频);
        this.Property(T =&GT; t.Id).HasColumnName(ID);
        this.Property(T =&GT; t.Description).HasColumnName(说明);
    }
}

然后我的控制器动作

 公众的ActionResult指数()
    {
        ViewBag.Message =欢迎使用ASP.NET MVC!;        使用(videoDBContext上下文=新videoDBContext())
        {
            VAR列表= context.Videos.ToList();
        }        返回查看();
    }

这将返回视频我添加到表什么的。

至于用什么去的地方,这并不重要,如果你在一个项目做的一切。选择一个点。这里的东西怎么在我震撼了。

您必须记住与code工作时,首先要得到的东西和运行有额外的前期工作。一旦你得到了它的窍门但是,它的使用数据库的一个非常好的途径。

I have looked at past questions on this but I can't solve my problem

I am having problems connecting a simple database to MVC project. This is very difficult to do and I am using VS2010, SQL Server 2008 (remote DB). I have a DB already created and I want to use code first with Entity Framework. Sounds easy as I just follow a tutorial but no tutorial I used has ever worked. The tutorials use older MVC and older Entity Framework. I have MVC4 and EF 5

Here are the steps I am using

  1. create new MVC project and in references I see Entity Framework

  2. create class which will correspond to a table not yet created in the DB

  3. add connection string to web.config

  4. add extra line to global.asax to avoid an error entity 5 throws up (found out about this from other peoples problems with this)

  5. add controller with db and dbcontext

  6. run project and as you could guess a problem occurs with controller called video

Error:

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.videos'.

I have no idea and this MVC seems a lot more unstable than web forms as I can connect to the same DB in webforms without an issue .

 <add  name="videoDBContext"
       connectionString="Data Source=xxxxxxx;Initial Catalog=xx;Persist Security Info=True;User ID=xx;    Password=xxx"
       providerName="System.Data.SqlClient" />

Class:

public class video
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

DBContext:

public class videoDBContext : DbContext
{
    public DbSet<video> videos{ get; set; }
}

Controller action

public ActionResult Index()
    {
        return View(db.videos.ToList()); //
  Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.videos'.
    }

解决方案

You're connecting to the Database fine. The actual DB model and the codefirst model are not in sync, hence the error.

You're adding a DbSet to the DBContext for video, but no such table exists within your current database. Unless your database initializer states to create the models when it does not exist, this is exactly the error I'd expect you to get.

Also, I see no mapping class defined or mentioned that maps the model class back to the database table.

Take a look at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application. This gets into database intializers towards the end. The other option is to simply create the table manually.

So, problem one, no database initializer (or pre-defined table). Problem two, no mapping class for the table and OnModelCreating, at least from what you've shown. It's entirely possible that you're not using the fluent api to define your mappings and instead are just using attributes in the video model, but again, you didn't show that, so I'm going to show you the fluent way.

EDIT:

I've updated this code from a test project I created locally with your naming conventions. This 100% works. These are the exact class I created or reverse engineered.

public class videoDBContext : DbContext
{
    static videoDBContext()
    {
        Database.SetInitializer<videoDBContext>(null);
    }

    public videoDBContext()
        : base("Name=videoDBContext")
    {
    }

    public DbSet<Video> Videos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new VideoMap());
    }
}

domain class

public class Video
{
    public int Id { get; set; }
    public string Description { get; set; }
}

and the mapping class

public class VideoMap : EntityTypeConfiguration<Video>
{
    public VideoMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Description)
            .IsRequired()
            .HasMaxLength(50);

        // Table & Column Mappings
        this.ToTable("Video");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Description).HasColumnName("Description");
    }
}

and then my controller action

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        using (videoDBContext context = new videoDBContext())
        {
            var list = context.Videos.ToList();
        }

        return View();
    }

This returns whatever "videos" I added to the table.

As for what goes where, it doesn't really matter if you're doing everything in one project. Pick a spot. Here's how things shook out in mine.

You have to remember there's additional upfront effort when working with code first to get things up and running. Once you get the hang of it however, it's a really nice way of working with databases.

这篇关于MVC4无法连接到SQL Server 2008中的远程数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆