簡體   English   中英

在控制台應用程序中重用來自我的 ASP.NET Core MVC 應用程序的代碼:如何進行數據庫連接

[英]Reusing code from my ASP.NET Core MVC app in console app : how to do database connection

我做了一個使用 Web 的 ASP.NET Core MVC 應用程序。 此應用程序讀取和寫入數據庫。

現在,我想在 .NET Core 中創建一個使用相同數據庫(服務器、連接字符串等)的控制台應用程序。

如何重用數據庫上下文的代碼來訪問與第一個應用程序相同的數據庫?

現在,我的 Program.cs 是基礎。 我想在這里插入准備數據庫連接的代碼...

編輯

我的數據上下文模型是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MVFxml;
using MVFxml.Models;
using MVFxml.Models.ViewModels;
//using MVFxml.Controllers;
using MVFxml.Infrastructure;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;

namespace MVFxml.Models
{
    public class fmDataContext : DbContext
    {
        private DbContextOptions<fmDataContext> opt { get; set; }

        public fmDataContext(DbContextOptions<fmDataContext> options)
            : base(options)
        {
            opt = options;
        }

        public MyStructure RetrieveFromDb(long id = -1)
        {
           … code here …
        }

        ...other fuctions here...
}

為了解決這個問題,我編寫了控制台應用程序的Main例程如下:

        static void Main(string[] args)
        {
            …
            var optionsBuilder = new DbContextOptionsBuilder<fmDataContext>();

            optionsBuilder
                .UseSqlServer(connectionString, providerOptions => providerOptions.CommandTimeout(60));

            using (fmDataContext context = new fmDataContext(optionsBuilder.Options))
            {
                MyStructure data = context.RetrieveFromDb();

                … // here I do whatever I want with the data
            }

而且我不必更改上面顯示的fmDataContext類...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM