【问题标题】:Entity Framework added s to my .dbo实体框架将 s 添加到我的 .dbo
【发布时间】:2012-08-03 15:55:11
【问题描述】:

我目前使用“Entity Framework DbContext”,但我遇到了异常 towars.dbo 未找到。这很奇怪,因为在我的网站上我一直在询问 towar.dbo 但没有 towars.dbo 你知道哪里有问题吗?

- InnerException    {"Invalid object name 'dbo.Towars'."}   System.Exception {System.Data.SqlClient.SqlException}

我关于 Towar 的所有事情(当然在我的程序中的位置不同):

public class ProductController : Controller
{
    //
    // GET: /Product/
        public ITowarRepository repository;

        public ProductController(ITowarRepository productRepository) 
        {
        repository = productRepository;
        }

        public ViewResult List()
        {
            return View(repository.Towar);
        }

}


public interface ITowarRepository
    {
        IQueryable<Towar> Towar { get; }
    }

public DbSet<Towar> Towar { get; set; }

public class EFTowarRepository : ITowarRepository
    {
        public EFDbContext context = new EFDbContext();
        public IQueryable<Towar> Towar
        {
            get { return context.Towar; }
        }
    }
public class Towar
    {
        [Key]
        public int Id_tow { get; set; }
        public string Nazwa { get; set; }
        public string Opis { get; set; }
        public decimal Cena { get; set; }
        public int Id_kat { get; set; }
    }

【问题讨论】:

  • 你在数据库中的表名是什么?你连接到正确的数据库了吗?
  • 连接数据库正确

标签: asp.net-mvc visual-studio-2010


【解决方案1】:

将以下行添加到您的上下文中:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

【讨论】:

  • 这是最好的方法,因为其他解决方案只是一次性修复。
【解决方案2】:

您可以告诉 EF 映射到表 Towar,方法是使用如下流式 API 覆盖 DBContext 类中的 OnModelCreating 方法:

public class EFDbContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Entity<Towar>().ToTable("Towar");
   }
}

现在 EF 将查找 Towar 表而不是 Towars。如果您没有创建这些表,则说明您遇到了其他问题。

【讨论】:

  • 感谢您的帮助 :) 我不明白他们为什么在 Visual Studio 中创建这个愚蠢的东西,但我很高兴您的帮助。
【解决方案3】:

EF Code First 自动将表名复数。使用[Table] 属性将实体显式映射到表名:

[Table("Towary")]
public class Towary
{
   // Whatever properties
}

看起来也有一种方法可以在全局上禁用复数,请参阅Entity Framework Code First naming conventions - back to plural table names?

【讨论】:

  • 错误 1“名称”不是有效的命名属性参数。命名属性参数必须是非只读、静态或 const 的字段,或者是公共而非静态的读写属性。 C:\Users\Rafal\Desktop\MVC ksiązka\moj projekt\sklep\SportsStore\Entities\Product.cs 9 12 SportsStore.Domain
  • 抱歉,我读错了文档。应该只是[Table("Towary")]
【解决方案4】:
using System.Data.Entity.ModelConfiguration.Conventions;

namespace MVCDemo.Models

     {
         public class EmployeeContext : DbContext

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

为了完整起见@四十二

【讨论】:

  • 有了你@Crismogram 的回复,我可以毫无问题地连接到远程数据库......很棒的方法......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2015-01-02
相关资源
最近更新 更多