안녕하세요.
37장 진행중 DB연동 문제가 발생하여 문의드립니다.(첨부된 사진과 같은 예외 발생.)
검색해보니 통상 ConnectionString 타이핑 오타 등의 문제던데, 아무리찾아봐도 해결을 할수가 없어서 문의드립니다..
Index, Create 등 모든 뷰에서 DB 연동이 되지 않는것 같습니다.
1. 커넥션스트링의 DefaultConnection 값을 의도적으로 틀리게 입력하는 경우에는 "SqlException: 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: 50 - Local Database Runtime error occurred. 지정된 LocalDB 인스턴스가 없습니다." 예외가 발생합니다.
2. NoteRepository의 생성자에서
con = new SqlConnection(_config.GetSection("cConnectionStrings").GetSection("DefaultConnection").Value);
이렇게 ConnectionString 값을 의도적으로 틀리게 입력하면,
An unhandled exception occurred while processing the request.
InvalidOperationException: The ConnectionString property has not been initialized.
System.Data.SqlClient.SqlConnection.PermissionDemand()
예외가 발생합니다.
어디가 잘못된걸까요...
교재는 asp.net core 프레임워크 버젼이 달라서 그런걸까요..
작성한 코드--------------------------------
1. 컨트롤러
DotNetNoteController.cs
[HttpGet]
public IActionResult Create()
{
ViewBag.FormType = BoardWriteFormType.Write;
ViewBag.TitleDescription = "글 쓰기 - 다음 필드들을 채워주세요.";
ViewBag.SaveButtonText = "저장";
return View();
}
2. NoteRepository 생성자
NoteRepository.cs
public NoteRepository(IConfiguration config, ILogger<NoteRepository> logger)
{
_config = config;
con = new SqlConnection(_config.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value);
_logger = logger;
}
3. ConnectionString
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetNote;Trusted_Connection=True;"
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=DotNetNote;Trusted_Connection=True;"
}
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
4. Configuration
Startup.cs
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);
services.AddSingleton<IConfiguration>(Configuration);
services.AddTransient<INoteRepository, NoteRepository>();
services.AddSingleton<INoteCommentRepository>(
new NoteCommentRepository(Configuration["ConnectionStrings:DefaultConnection"]));
}
5. View
_BoardEditorForm.cshtml
@model Note
<div class="form-horizontal">
@if (ViewBag.FormType == DotNetNote.Models.BoardWriteFormType.Modify)
{
<div class="form-group">
<label asp-for="Id" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Id" class="form-control" style="border:0; width:100px;" maxlength="10" readonly />
<input type="hidden" name="Id" value="@Model.Id" />
</div>
</div>
}
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" style="width:150px;" maxlength="10" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
6. 프로젝트
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.78" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DotNetNote.Dul\DotNetNote.Dul.csproj" />
</ItemGroup>
</Project>