SqlException(0x80131904):无效的对象名称'dbo.Categories'

时间:2011-03-21 06:27:08

标签: c# sql-server asp.net-mvc entity-framework asp.net-mvc-3

我在运行应用程序时遇到上述异常。该应用程序使用的是asp.net mvc 3 / C#。我制作了一个mdf文件并将其添加到Visual Web Developer Express中的App_Data文件夹下。我在web.config文件夹中添加了连接字符串,但是当我运行并浏览到/ store时,我得到上面的错误,突出显示了行var categories = storeDB.Categories.ToList();。我的数据库包含6个表,其中一个是Category。

控制器:

EventCalendarEntities storeDB = new EventCalendarEntities();

public ActionResult Index()  
{  
    var categories = storeDB.Category.ToList();  
    return View(categories);  
}    

web.config文件中的连接字符串:

<connectionStrings>
   <add name="EventCalendarEntities"
        connectionString="data source=.\SQLEXPRESS;
        Integrated Security=SSPI;
        AttachDBFilename=|DataDirectory|\MvcEventCalendar.mdf;
        User Instance=true"
        providerName="System.Data.SqlClient" />
</connectionStrings>

6 个答案:

答案 0 :(得分:22)

这通常意味着一个简单的配置问题:

  • 也许真的没有这样的表
  • 也许表格在那里,但没有dbo方案(可能在Fred.Categories中)
  • 也许数据库区分大小写(很好),表实际上是dbo.CATEGORIES

任何这些都会导致上述异常。特别是,您声明:

  

我的数据库包含6个表,其中一个是Category。

现在转到计算机Category!= Categories

答案 1 :(得分:6)

尝试使用模型构建器类。它是配置或显式定义表和模型类之间映射的方法。

在您的实体/上下文类中尝试添加此代码

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       base.OnModelCreating(modelBuilder);
       modelBuilder.Entity<Category>().ToTable("Category");
    }

它是一种方法。请确保使用所有包含的语句。

答案 2 :(得分:2)

你真正想要解决的问题是Context class你应该有一个名为OnModelCreating的方法...确保它有这个:

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

答案 3 :(得分:2)

由于这仍然是2018年4月例外的最佳搜索,它引导我找到解决方案,让我在特定情况下解决这个问题......

我们的应用程序基于ABP和ABP.Zero,我们已经有一个适合Marc's answer的模式。虽然我打赌在OnModelCreating方法(la Dhananjay's answer)中的显式映射本可以完美地工作,但似乎ABP的映射在这一点上完美地工作并且我不想打破图案。

我的解决方案是向实体类添加一个表属性,这解决了EF的困惑。

using System;
using Abp.Domain.Entities;
using System.ComponentModel.DataAnnotations.Schema;

namespace Discovery.History
{

    [Table("HistoryRecords")]
    public class HistoryRecord : Entity<int>
    {
        public int ResearcherCount { get; set; }
        public DateTime DateSubmitted { get; set; }
        public string Comments { get; set; }
    }
}

答案 4 :(得分:1)

经过验证,测试过的&amp;验证具有名称类别的表或任何名为table的SQL关键字使用ToTable指示特定的表名

layer.enabled: true

答案 5 :(得分:0)

如果你有一个没有 this.Map.(a table in db necessary to mapping) 的映射属性和键的类,EntityFramework 期望你有一个类似于 Category 的表,但转换为复数,所以“Categories”..要解决你可以添加 this.Map(in correct table existing in your DB) .

相关问题