SqlException:无效的对象名称' dbo.TblDepartments'。表名复数

时间:2018-05-08 04:24:48

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

我正在使用带有SQL Server数据库和TblDepartment的ASP.NET MVC。

当我加载Register页面时,出现错误:

  

SqlException:无效的对象名称' dbo.TblDepartments'

在我的所有代码中,我将表格称为TblDepartment,但错误出现在TblDepartments(最后带有s)。

现在,当我在SQL Server中将TblDepartment重命名为TblDepartments时,一切正常。有没有人见过这种问题?

这是我的代码:

TblDepartment.cs

namespace WebApp1.Models
{
    public class TblDepartment
    {
        [Key]
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }
}

AccountViewModels.cs

public class RegisterViewModel
{
    [Display(Name = "Department")]
    public int DeptId { get; set; }

    [ForeignKey("DeptId")]
    public TblDepartment TblDepartment { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

}

IdentityModels.cs

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

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

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

Register.cshtml

@Html.DropDownList("DeptId", null, "", new { @class = "form-control" })

AccountController.cs

// GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        ViewBag.DeptId = new SelectList(db.TblDepartment.ToList(), "DeptId", "DeptName");
        return View();
    }

1 个答案:

答案 0 :(得分:1)

实体框架自动添加&#34; S&#34;到SQL Server表名。 EF对表名使用PluralizingTableNameConvention规则。

您可以使用TableMapping

显式设置表名
  1. 您可以使用数据注释配置类型映射到的表

    [Table(Name = "TblDepartment")]
    public class TblDepartment
    {
        [Key]
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }
    
  2. 您可以使用Fluent API配置类型映射到的表。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TblDepartment>()
             .ToTable("TblDepartment");
    }
    
  3. 您可以关闭EF复数约定的另一个选项

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