zoukankan      html  css  js  c++  java
  • ASP.NET MVC3 + Entity Framework表名变为复数形式解决方法(转)

    原文地址: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; }
        }
    }


    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为实体类指定映射的表名

    [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; }
    }


    方法二:重写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; }
    }
  • 相关阅读:
    构建自己的C/C++插件开发框架(四)——核心层设计和实现
    构建自己的C/C++插件开发框架(二)——总体功能
    对企业来说,要放在第一位的是什么
    深入理解C++的动态绑定和静态绑定
    构建自己的C/C++插件开发框架(三)——总体结构
    管道和过滤器
    层模式——面向模式的体系结构学习笔记
    使用信元流(TLVStream)规范、简化模块(C/C++)间交互
    推荐博客
    Android 操作系统的内存回收机制
  • 原文地址:https://www.cnblogs.com/zyhblogs/p/3800673.html
Copyright © 2011-2022 走看看