原文地址:http://www.mzwu.com/article.asp?id=3286
今天尝试用ASP.NET MVC3 + Entity Framework写个demo,结果运行出错。在寻找原因的过程中我对代码逐步简化,最终代码如下:
UserModels.cs:
复制内容到剪贴板 程序代码
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MvcApplication1.Models
{
public class User
{
[Key]
public int Id { get; set; }
public string Usn { get; set; }
public string Pwd { get; set; }
public DateTime Created { get; set; }
}
public class UserContext : DbContext
{
public UserContext()
: base("Name=SQLServer")
{ }
public DbSet<User> User { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MvcApplication1.Models
{
public class User
{
[Key]
public int Id { get; set; }
public string Usn { get; set; }
public string Pwd { get; set; }
public DateTime Created { get; set; }
}
public class UserContext : DbContext
{
public UserContext()
: base("Name=SQLServer")
{ }
public DbSet<User> User { get; set; }
}
}
UserController.cs:
复制内容到剪贴板 程序代码
using System.Linq;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class UserController : Controller
{
private UserContext db = new UserContext();
public ActionResult Index()
{
Response.Write(db.User.Count().ToString());
return new EmptyResult();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class UserController : Controller
{
private UserContext db = new UserContext();
public ActionResult Index()
{
Response.Write(db.User.Count().ToString());
return new EmptyResult();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
运行结果:
很奇怪,为什么表名不是User,自动加上了s变成复数形式Users了呢?
ASP.NET MVC3 + Entity Framework表名变为复数形式解决方法
方法一:使用TableAttribute为实体类指定映射的表名
复制内容到剪贴板 程序代码
[Table("User")]
public class User
{
[Key]
public int Id { get; set; }
public string Usn { get; set; }
public string Pwd { get; set; }
public DateTime Created { get; set; }
}
public class User
{
[Key]
public int Id { get; set; }
public string Usn { get; set; }
public string Pwd { get; set; }
public DateTime Created { get; set; }
}
方法二:重写OnModelCreating方法不允许将表名变为复数形式
复制内容到剪贴板 程序代码
public class UserContext : DbContext
{
public UserContext()
: base("Name=SQLServer")
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
public DbSet<User> User { get; set; }
}
{
public UserContext()
: base("Name=SQLServer")
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
public DbSet<User> User { get; set; }
}