代码之家  ›  专栏  ›  技术社区  ›  Xam Eseerts

实体框架核心-如何访问上下文。数据库迁移()

  •  2
  • Xam Eseerts  · 技术社区  · 7 年前

    我刚刚开始使用EF Core和Net Core,遇到了一个我找不到任何答案的问题。

    我正在开发一个控制台应用程序,它使用SQLite数据库进行存储。我现在正在测试,在上下文中工作很好。下面的示例程序运行良好。注意,我最初确实使用了迁移来创建数据库。

    现在,当我最终完成这个应用程序时,我想确保数据库存在。正如在其他帖子中读到的,这应该用 ctx.Database.Migrate() . 然而,我还无法访问此方法。所以我的问题是,我必须做什么才能访问它?我是否缺少添加扩展方法的包?我需要配置更多的东西吗?

    请原谅这个非常基本的问题,但我找不到关于这个的任何东西。所以,如果我只是不知道去哪里找,我也会很高兴有一个阅读推荐。

    using System;
    using MyLog.NetCore.Models;
    using MyLog.NetCore.DataAccess;
    
    namespace MyLog.NetCore
    {
        internal class Program
        {
            #region Private Methods
    
            private static void Main(string[] args)
            {
                using (var ctx = new MyLogContext())
                {
                    ctx.Add(new PartialLogEntry { PartialLogEntryID = 1, StartDateTime = 1, Title = "Test" });
                    var count = ctx.SaveChanges();
                    Console.WriteLine($"{count} changes saved to database!");
    
                    Console.WriteLine();
                    Console.WriteLine("All partial lof entries in database:");
                    foreach (var entry in ctx.PartialLogEntries)
                    {
                        Console.WriteLine($"ID: {entry.PartialLogEntryID}\tStart: {entry.StartDateTime}\tTitle: {entry.Title}");
                    }
                }
    
                Console.ReadLine();
            }
    
            #endregion Private Methods
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  6
  •   Ivan Stoev    7 年前

    许多EF核心方法被实现为扩展方法。因此,要使其可用,您首先需要:

    using Microsoft.EntityFrameworkCore;
    

    此特定方法在中定义 RelationalDatabaseFacadeExtensions 居住在 Microsoft.EntityFrameworkCore.Relational 程序集,因此请确保您正在引用它。

    推荐文章