Początki z .Net Core i Microsoft Sql Server - jak to połączyć?

0

Mianowicie tak, mam postawione lokalnie serwer Microsoft Sql Server,utworzone tabele i rekordy w Microsoft Sql Server Management Studio widzę w Visual Studio w SQL Server Object Explorerze.
Chciałbym teraz wiedzieć jak mogę użyć danych - czy muszę się łączyć z tą bazą z kodu?
Chciałbym uzyskać taki efekt bym mógł mieć query zapisane w plikach sql i potem tylko je wywołuję, ale najpierw mi zależy bym miał pewność że jest połączenie z bazą.

1

Chciałbym uzyskać taki efekt bym mógł mieć query zapisane w plikach sql i potem tylko je wywołuję,

to nie jest dobry pomysl

poczytaj o code first

0

Właśnie próbuje coś pokombinować z tym codefirst.
Znajomy mówił że po prostu tworze bazę danych w projekcie jako nowy obiekt po instalacji Entity Framework ale ja nie mam takiej opcji.

0

Przy próbie z poradnika wyżej:

Add-Migration InitialCreate
Update-Database

Taki efekt:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

Co dalej?

1

Bazę utwórz przy pomocy context.Database.EnsureCreated()

https://stackoverflow.com/questions/38238043/how-and-where-to-call-database-ensurecreated-and-database-migrate

No chyba, że bardzo chcesz tymi migracjami, to wtedy musisz nadpisać OnConfiguring:

https://stackoverflow.com/a/48484797

0

Po kilku poprawkach taki komunikat:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using PersonalTrainer.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;

namespace PersonalTrainer
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var connection = @"Server=(localdb)\mssqllocaldb;Database=PersonalTrainer.Models;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<MenuContext>
                (options => options.UseSqlServer(connection));
            // BloggingContext requires
            // using EFGetStarted.AspNetCore.NewDb.Models;
            // UseSqlServer requires
            // using Microsoft.EntityFrameworkCore;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("test");
            });
        }
    }
}

1

Jeżeli już ogarnąłeś dlaczego Ci się nie łączy, to teraz

Do parametrów Configure dodaj ten swój context, a później w metodzie wywołaj na nim context.Database.EnsureCreated()

public void Configure(IApplicationBuilder app, IHostingEnvironment env, Mycontext context)
{
    context.Database.EnsureCreated();
}

I ci utworzy bazę jeżeli jej nie będzie.

0

Startup.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Database.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;

namespace PersonalTrainer
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var connection = @"Server=(localdb)\mssqllocaldb;Database=PersonalTrainer.Models;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<Database.Model.AppContext>
                (options => options.UseSqlServer(connection));
            // BloggingContext requires
            // using EFGetStarted.AspNetCore.NewDb.Models;
            // UseSqlServer requires
            // using Microsoft.EntityFrameworkCore;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("test");
            });
        }
    }
}

Model.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Database.Model
{
    public class AppContext : DbContext
    {
        public AppContext(DbContextOptions<AppContext> options) : base(options)
        { }

        public DbSet<Menu> Menus { get; set; }

    }
    public class Menu
    {
        public string ID { get; set; }
        public string ParentID { get; set; }
        public string Content { get; set; }
        public string IconClass { get; set; }
        public string Url { get; set; }
        public long Order { get; set; }
    }
}

Dodałem ten context jak pisałeś i dalej jest ten sam błąd że nie ma połączenia z serwerem SQL.

1

Czemu po prostu nie odpaliłeś jakiegoś kursu .NET Core + Entity Framework gdzie jest wytłumaczone wszystko po kolei, tylko prosisz innych, aby ci wskazali podstawy? :P

0

Robię jakiś projekt więc nie robię 1 : 1 tak jak w poradnikach, tylko staram się już robić jakieś podstawy pod projekt. Efektem tego jest to, że czasem jest coś inaczej albo znajduje poradniki gdzie jest inna baza, a to inna wersja. Uwierz mi, mam odpalone kilka ale jeszcze nie zdarzyło mi się bym z jednego poradnika napisał całą funkcjonalność którą chcę zrobić :)

Przykładowo w tym poradniku:

https://docs.microsoft.com/pl-pl/ef/core/get-started/aspnetcore/new-db?tabs=visual-studio

Nie wynika z niego jak mam wczoraj utworzoną bazę aktualizować o nowe tabele dlatego też szukam teraz rozwiązania i jednocześnie pytam :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1