C# 实体框架异常:无效的对象名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11581147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:26:56  来源:igfitidea点击:

Entity Framework Exception: Invalid object name

c#.netentity-framework

提问by LCJ

I am trying to create database using Code First approach. When I run the following code I am getting the following exception. Is there anything wrong in the fields that I defined? How can we overcome this?

我正在尝试使用 Code First 方法创建数据库。当我运行以下代码时,出现以下异常。我定义的字段有什么问题吗?我们怎样才能克服这个问题?

Exception:

例外

An error occurred while updating the entries. See the inner exception for details.

更新条目时出错。有关详细信息,请参阅内部异常。

Inner Exception:

内部异常

"Invalid object name 'dbo.Dinners'.

“无效的对象名称 'dbo.Dinners'。

Note: I do not have such a table (Dinners) in the database. The code is supposed to create the tables. I just gave connection string to identify the server as mentioned in EF Code First: Cannot connect to SQL Server. Should I change the connection string?

注意:我在数据库中没有这样的表(Dinners)。该代码应该创建表。我只是提供了连接字符串来标识EF Code First: Cannot connect to SQL Server 中提到的服务器。我应该更改连接字符串吗?

Connections String:

连接字符串:

string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.

LibraryReservationSystem 数据库已是现有数据库。它没有桌子。我期待 EF 创建表。

The connection string I copied from a working LINQ 2 SQL application. Do I need to make any changes to it to supply to EF?

我从一个工作的 LINQ 2 SQL 应用程序复制的连接字符串。我是否需要对其进行任何更改才能提供给 EF?

enter image description here

在此处输入图片说明

UPDATE

更新

When I included the following code, the exception got changed. Now it says - "Invalid object name 'dbo.Dinner'.". It is now complaining about Dinner table; not Dinners table.

当我包含以下代码时,异常发生了变化。现在它说 - “无效的对象名称'dbo.Dinner'。”。现在在抱怨餐桌;不是餐桌。

    protected override void OnModelCreating(DbModelBuilder modelbuilder)
    {
        modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

Original CODE

原始代码

    static void Main(string[] args)
    {

        string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

        using (var db = new NerdDinners(connectionstring))
        {
            var product = new Dinner { DinnerID = 1, Title = 101 };
            db.Dinners.Add(product);
            int recordsAffected = db.SaveChanges();
        }

    }


using System.Data.Entity;
namespace LijosEF
{
public class Dinner
{
    public int DinnerID { get; set; }
    public int Title { get; set; }

}

public class RSVP
{
    public int RSVPID { get; set; }
    public int DinnerID { get; set; }

    public virtual Dinner Dinner { get; set; }
}

//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{

    public NerdDinners(string connString): base(connString)
    { 

    }

    public DbSet<Dinner> Dinners { get; set; }
    public DbSet<RSVP> RSVPs { get; set; }
}
}

REFERENCE

参考

  1. http://nerddinner.codeplex.com/discussions/358197
  2. Entity framework - Invalid Object Name
  3. Invalid object name 'dbo.TableName' when retrieving data from generated table
  4. http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx
  1. http://nerddinner.codeplex.com/discussions/358197
  2. 实体框架 - 无效的对象名称
  3. 从生成的表中检索数据时,对象名称“dbo.TableName”无效
  4. http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx

采纳答案by Slauma

The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.

LibraryReservationSystem 数据库已是现有数据库。它没有桌子。我期待 EF 创建表。

That's not correct. If the database exists EF doesn't create any tables in this database. EF can create the database if it doesn't exist. That is the default database initializer CreateDatabaseIfNotExiststhat gets applied if you don't change it explicitly. You can select two other initializers: DropCreateDatabaseAlwaysor DropCreateDatabaseIfModelChanges. But neither of those will only create tables in an existing database but instead delete the database completely and create it from scratch including all tables.

那不正确。如果数据库存在,EF 不会在该数据库中创建任何表。如果数据库不存在,EF 可以创建它。这是默认的数据库初始值设定项CreateDatabaseIfNotExists,如果您不显式更改它,则将应用该初始值设定项。您可以选择另外两个初始值设定项:DropCreateDatabaseAlwaysDropCreateDatabaseIfModelChanges。但是这些都不会只在现有数据库中创建表,而是完全删除数据库并从头开始创建它,包括所有表。

What can you do:

你能做什么:

  • Either delete the database manually (in SSMS for example), then EF will create a new one including the tables
  • Or use the DropCreateDatabaseAlwaysinitializer onceto let EF create the database including the tables, then remove the initializer again
  • Or if you can't delete the database for whatever reason write SQL code in the Seedmethod that adds the tables to the database(Wrong, thanks to Mark Stafford's comment)
  • Or use Code-First Migrations(EF >= 4.3) to add new tables to an existing database when you have added new entities.
  • 手动删除数据库(例如在 SSMS 中),然后 EF 将创建一个包括表的新数据库
  • 或者使用DropCreateDatabaseAlways初始化器一次让 EF 创建包含表的数据库,然后再次删除初始化器
  • 或者,如果由于某种原因无法删除数据库,请在Seed将表添加到数据库的方法中编写 SQL 代码(错误,感谢 Mark Stafford 的评论)
  • 或者,在添加新实体后,使用代码优先迁移(EF >= 4.3) 将新表添加到现有数据库。

回答by Gavin

As the error suggests, you do not have a table called Dinnerswithin your database.

正如错误所暗示的那样,您Dinners的数据库中没有调用表。

Are you using Single or Plural table names? i.e. Dinner or Dinners?

您使用的是单表名还是复数表名?即晚餐或晚餐?

回答by Sasha

As I understood, you are expecting the code to create DB automatically based on your entities description. But this will not happen unless you create DB explicitly. Please check the following link http://www.simple-talk.com/dotnet/.net-framework/entity-framework-4460---learn-to-create-databases-from-the-model/and this tutorial on EF codefirst: http://codefirst.codeplex.com/

据我了解,您希望代码根据您的实体描述自动创建数据库。但这不会发生,除非您明确创建 DB。请检查以下链接http://www.simple-talk.com/dotnet/.net-framework/entity-framework-4460---learn-to-create-databases-from-the-model/和本教程EF 代码优先:http://codefirst.codeplex.com/

回答by Mark Stafford - MSFT

@Slauma's answer is the right one - the tables are created upon initialization. It's probably easiest to just delete the database and let EF create it (if you leave your connection string as is, it will create a database called LibraryReservationSystem on the local machine; you should probably specify an explicit host name if you're going to use the connection string in the config at this point).

@Slauma 的答案是正确的 - 表是在初始化时创建的。删除数据库并让 EF 创建它可能是最简单的(如果您将连接字符串保留原样,它将在本地计算机上创建一个名为 LibraryReservationSystem 的数据库;如果您要使用,您可能应该指定一个显式主机名此时配置中的连接字符串)。

You would need something along the lines of:

你需要一些类似的东西:

public class NerdDinnersInitializer : DropCreateDatabaseIfModelChanges<NerdDinners> { }

And you would also need to set the initializer in your Main method:

您还需要在 Main 方法中设置初始化程序:

Database.SetInitializer(new NerdDinnersInitializer());

Word to the wise: NEVER deploy an application with an initializer like the one above. You can see this blog postabout how to control initializers via the config file for more details on how to control this in production applications.

明智之言:永远不要使用像上面那样的初始化程序来部署应用程序。您可以查看这篇关于如何通过配置文件控制初始值设定项的博客文章,以了解有关如何在生产应用程序中控制它的更多详细信息。

回答by Renats Stozkovs

Once you have your entities designed you can right-click the workspace of the EDMX file and select 'Generate Database from Model...'. Click through until you have a script in your window. For that script you will have to remove DB creation step (if it is there) and go straight for CREATE TABLE ...

设计好实体后,您可以右键单击 EDMX 文件的工作区,然后选择“从模型生成数据库...”。单击直到您的窗口中有一个脚本。对于该脚本,您必须删除数据库创建步骤(如果存在)并直接执行 CREATE TABLE ...

Copy-Paste and execute in whatever DB you've got. You might have to adjust the script for a specific RDBMS.

复制粘贴并在您拥有的任何数据库中执行。您可能需要为特定的 RDBMS 调整脚本。

回答by Brett

I've just ran into the exact same issue - I'd already created my database on a development SQL box inside our network that needs SQL authentication.

我刚刚遇到了完全相同的问题 - 我已经在需要 SQL 身份验证的网络内的开发 SQL 框中创建了我的数据库。

When I ran my app, no tables were created. I found this awesome but simple article about creating a Code First Database Initializer Strategywhich first checks to see if the database exists and then runs a script against the database to create the tables.

当我运行我的应用程序时,没有创建表。我发现了这篇关于创建Code First 数据库初始化器策略的很棒但简单的文章,该策略首先检查数据库是否存在,然后针对数据库运行脚本以创建表。

As stated in the article - pay attention that when such a strategy is deployed, whenever the application starts over, all the database tables will be recreated! This strategy should only run once.

正如文章中所述——注意,当部署这样的策略时,每当应用程序重新启动时,所有数据库表都会重新创建!这个策略应该只运行一次。

But you already knew that.

但你已经知道了。