Entity Framework表名默认自动变为复数形式等常见问题解决方法

今天使用了一下手写EntityFramework,发现一些常见的问题,做个记录:

1、以前使用模板生成不太在意的问题,就是在定义实体类时,如果没映射注释,自动映射的表名会变成复数形式

如:表名==>表名s

这样就会报找不到表的异常,因为确实没这个加了复数的表名

解决方法:

1) 重写自动映射的方法:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace Linq2Mysql
{
    public class MyContext : DbContext
    {
        public MyContext()
            : base("name=MyContext")//web.config中connectionstring的名字
        {
        }

        public DbSet<article> Article { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

  

  

2) 添加映射表名注释

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Linq2Mysql
{
    [Table("article")]
    public class article
    {
        [Key]
        public int aid { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public DateTime create_time { get; set; }
        public DateTime update_time { get; set; }
        public string author { get; set; }
        public string sub_title { get; set; }
        public string editor { get; set; }
        public int status { get; set; }
        public int type_id { get; set; }
        public string picture_small { get; set; }
        public string sumary { get; set; }
    }
}

  

参考地址:https://blog.csdn.net/bensidiyu/article/details/46742329

2、在定义实体时,要添加关键字段注释,要不会报key未定义异常

EntityType 'aritcle' has no key defined. Define the key for this EntityType.

 [Key]
 public int aid { get; set; }

仅此做个记录,后面如果有使用问题会再做补充。

原文地址:https://www.cnblogs.com/mxm2005/p/8655763.html