我正在使用带有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();
}
答案 0 :(得分:1)
实体框架自动添加&#34; S&#34;到SQL Server表名。 EF对表名使用PluralizingTableNameConvention规则。
您可以使用TableMapping
显式设置表名您可以使用数据注释配置类型映射到的表
[Table(Name = "TblDepartment")]
public class TblDepartment
{
[Key]
public int DeptId { get; set; }
public string DeptName { get; set; }
}
您可以使用Fluent API配置类型映射到的表。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TblDepartment>()
.ToTable("TblDepartment");
}
您可以关闭EF复数约定的另一个选项
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}