Thứ Sáu, 14 tháng 7, 2017

Bắt đầu một project .Net Core

Môi trường sử dụng vs 2015
Áp dụng với database có sẵn
  • File -> New -> Project...
  • From the left menu select Installed -> Templates -> Visual C# -> Web
  • Select the ASP.NET Core Web Application (.NET Core) project template
  • Enter EFGetStarted.AspNetCore.ExistingDb as the name and click OK
  • Wait for the New ASP.NET Core Web Application dialog to appear
  • Under ASP.NET Core Templates 1.1 select the Web Application
  • Ensure that Authentication is set to No Authentication
  • Click OK
Chạy 3 gói package nuget
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design


sử dụng 

Scaffold-DbContext "Data Source=.\DEV1;Initial Catalog=Blogging;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -context BloggingContext

====Error


====
Rắc rối về phiên bản xuất hiện, giải pháp là chuyển hẳn sang visual 2017.

Chuyển sang visual 2017 mọi thứ đơn giản hơn


-OutputDir Models : Folder Models chứa class
-Context BloggingContext : Context name

Xem lại một chút file Context

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer(@"Data Source=.\DEV1;Initial Catalog=Blogging;User ID=sa;Password=123456");
        }
Tham khảo link http://go.microsoft.com/fwlink/?LinkId=723263  tạo  một kết nối an toàn với lý do bảo vệ thông tin nhạy cảm của chuỗi kết nối.

Trong appsettings.js tạo thêm một chuỗi connectionstring

{
  "ConnectionStrings": {
    "BloggingDatabase": "Data Source=.\\DEV1;Initial Catalog=Blogging;User ID=sa;Password=123456"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Trong Startup.cs khai báo using Microsoft.EntityFrameworkCore;

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddDbContext<BloggingContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
        }

Test bước đầu tiê n xem kết nối thành công, trong HomeController 
 private BloggingContext _bloggingContext;

        public HomeController(BloggingContext bloggingContext)
        {
            _bloggingContext = bloggingContext;
        }
        public IActionResult Index()
        {
            var model = _bloggingContext.Blog.ToList();
            return View(model);
        }


Không có nhận xét nào:

Đăng nhận xét

Subscribe

Flickr