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; }
}
}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);
}
}
}运行结果:

很奇怪,为什么表名不是User,自动加上了s变成复数形式Users了呢?
ASP.NET MVC3 + Entity Framework表名变为复数形式解决方法
方法一:使用TableAttribute为实体类指定映射的表名
[color=Green][Table("User")][/color]
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")
{ }
[color=Green]protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}[/color]
public DbSet<User> User { get; set; }
}
评论(0)
暂无评论。