简体   繁体   中英

Already an object named “Accounts” in the database (ASP.NET MVC)

I have looked at the other questions with this title but they all say to delete the table. I don't want to delete it, it has important data.

Instead, can't I make MVC stop trying to recreate it in the first place? I just want to read its data and output it. I am just trying to output it like this:

return View(db.Accounts.ToList());

This is my model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcApplication1.Models
{
    public class Account
    {
        public int ID { get; set; }
    }

    public class MyDbContext : DbContext
    {
        public DbSet<Account> Accounts { get; set; }
    }
}

How can I stop MVC from trying to recreate my table?

What is happening is MVC is checking the database and seeing that you do not have an account object in the database with only one column, ID in your case. So MVC is trying to create that object for you. What you need to do in order to use the existing table structure is to make your object match what is already in the database.

You can also create a temporary database and create your object with only one property(column). That allow you to see if your connection string is correct.

Try to map the your account class to the existing table by overriding the OnModelCreating() method in your context class

public class MyDbContext : DbContext
{
    public DbSet<Account> Accounts { get; set; }

    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        modelBuilder.Entity<Account>( ).ToTable( "dbo.Accounts" );
        //and perhaps the columns as well
        modelBuilder.Entity<Account>( ).Property( p => p.Id )
                                       .HasColumnName( "Id" );
}

That should tell Entity Framework to use your existing table, rather that try to create a new one. Mapping every column shouldn't be necessary.

Be sure the strings you pass to the ToTable() and HasColumnName() methods match exactly what is in your database.

in the Global.asax put the following line in the Application_Start()

Database.SetInitializer(null);

this will prevent from creating the table I hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM