木子屋 Dnawo's BLOG

ASP.NET MVC3 + Entity Framework表名变为复数形式解决方法

👤 dnawo 📅 2012-08-10 👁 10242 👍 0 💬 0 🔄 本站原创
今天尝试用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; }
    }
}

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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 SQL Server添加/删除/修改列示例 下一篇 → ASP.NET MVC3 Razor视图引擎基本语法学习小结