c# - 使用 Entity Framework 和 MYSQL 自动创建表(代码优先)

标签 c# mysql asp.net

我写这篇文章是因为我需要有关 ASP.NET Core MVC 应用程序的帮助。我正在使用具有身份的 Entity Framework

这是dbcontext 类。设置DbSet仅用于测试。这里 Identity 必须自动创建所有表,例如 AspNetUsersAspNetRoles 等,就像使用 Sql Server 一样,称为

代码优先如果我没记错的话。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<SettingsDataModel> Settings { get; set; }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Fluent API
            modelBuilder.Entity<SettingsDataModel>().HasIndex(a => a.Name);
        }
    }

因此,我创建了数据库类,ASP.NET 应用程序在此处初始化数据库:

        services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySQL(IoCContainer.Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

启动类(class)中。请注意,我使用 MySql 是因为我将在 Google Cloud Platform 上的 App Engine 中托管应用程序,这就是代码具有 .UseMySQL 的原因。 在 HomeController 中,我执行 EnsureCreated 方法。

    protected ApplicationDbContext mContext;

    protected UserManager<ApplicationUser> mUserManager;

    protected SignInManager<ApplicationUser> mSignInManager;

    public HomeController(
        ApplicationDbContext context,
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager)
    {
        mContext = context;
        mUserManager = userManager;
        mSignInManager = signInManager;
    }

    public IActionResult Index()
    {
        mContext.Database.EnsureCreated(); //<-- It returns false

        if (!mContext.Settings.Any()) //<-- Here it throws an exception saying that the database no exists
        {
            mContext.Settings.Add(new SettingsDataModel
            {
                Name = "BackgroundColor",
                Value = "Red"
            });

            mContext.SaveChanges();
        }

        return View();
    }

我希望我的解释正确,并且我提供了解决问题所需的所有类。

最佳答案

在您的 ApplicationDbContext 类中,确保将所有需要的类添加为公共(public)属性,例如 Settings 表。

public DbSet<PeopleDataModel> People { get; set; }

之后,您需要运行 Add-Migration AddPeople 命令来创建包含新更改的新迁移类,然后运行 ​​Update-Database 命令来应用挂起的迁移到数据库。

关于c# - 使用 Entity Framework 和 MYSQL 自动创建表(代码优先),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824816/

相关文章:

c# - Java枚举支持方法?但不是在 C# 中?

c# - 此应用程序需要以下版本之一的 .NET Framework

c# - RX2.0 : ObjectDisposedException after diposing EventLoopScheduler

mysql - 删除其中一些后修复 mysql 表行 id 中的间隙

c# - 如何使用 RichText 在 EPPlus 的单个单元格中获取换行符

php - mysql_query如何与一个 "dynamic"数据库一起使用呢?

mysql - 从 MySQL 中的字符串中提取日期

c# - 具有多个分隔符的条件分割字符串

ASP.NET Windows 身份验证模拟问题

asp.net - 插入和更新问题