且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC4无法连接到SQL Server 2008中的远程数据库

更新时间:2022-11-30 09:08:34

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

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

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

看看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< videoDBContext>(NULL);
    }    公共videoDBContext()
        :基地(NAME = videoDBContext)
    {
    }    公共DbSet<视频>影片{搞定;组; }    保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        modelBuilder.Configurations.Add(新VideoMap());
    }
}

域类

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

和映射类

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

然后我的控制器动作

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

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

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

MVC4无法连接到SQL Server 2008中的远程数据库

您必须记住与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.