Last active
March 29, 2017 21:32
-
-
Save A-Programmer/4597bc0d8122067ab54484afd70b9843 to your computer and use it in GitHub Desktop.
Adding model and DbContext to .Net Core Project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First of all install vscode-nuget-package-manager Extension. | |
Open .cspro file | |
Press Ctrl + Shift + P and type >NuGet Package MAnager: Add Package | |
Type Microsoft.EntityFrameworkCore.SqlServer | |
use dotnet restore | |
Create database 'MyDatabase' and a table called MyModels with 3 fields (Id, FullName,Email) | |
Add 'Models' folder and 'MyDbContext.cs' and 'MyModel.cs' files in it | |
Open MyModel.cs and add this codes : | |
using Microsoft.EntityFrameworkCore; | |
namespace ProjectName | |
{ | |
public class MyModel | |
{ | |
public int Id { get; set; } | |
public string FullName { get; set; } | |
public string Email { get; set; } | |
} | |
} | |
Now open MyDbContext.cs and add this codes: | |
using Microsoft.EntityFrameworkCore; | |
namespace ProjectName | |
{ | |
public class MyDbContext : DbContext | |
{ | |
public DbSet<MyModel> MyModels { get; set; } | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
optionsBuilder.UseSqlServer(@"Data Source=.;Initial Catalog=MyDatabaseName;Persist Security Info=True;User ID=DatabaseUserName;Password=DatabasePassword"); | |
} | |
} | |
} | |
***** Another way for getting connection string is this : | |
Create appsettings.json file and write your connection string like this: | |
{ | |
"ConnectionStrings": | |
{ | |
"SampleConnection": "Data Source=.;Initial Catalog=MyTestDb;Persist Security Info=True;User ID=sa;Password=123" | |
} | |
} | |
Now in MyDbContext.cs you can write this code in OnConfiguring method : | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); | |
var configuration = builder.Build(); | |
string connectionString = configuration.GetConnectionString("SampleConnection"); | |
optionsBuilder.UseSqlServer(connectionString); | |
Ok, just open your controller and write your usual codes, for example : | |
public IActionResult About() | |
{ | |
using(var db = new MyDbContext()) | |
{ | |
var data = new MyModel {FullName = "Kamran", Email = "[email protected]"}; | |
db.MyModels.Add(data); | |
db.SaveChanges(); | |
var users = db.MyModels.ToList(); | |
ViewData["Message"] = users.Count().ToString(); | |
} | |
return View(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment