-
Create a solution with Visual Studio 2017 and add a new .NET Class Library project.
- Select Windows Classic Desktop, Class Library
- Specify a .NET Framework version (for ex, 4.7)
- Add the EF6 NuGet package.
-
Add a
Product
entity class to a Models folder.public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } }
-
Add a
SampleDbContext
to a Contexts folder and inherit fromDbContext
.-
Add a
Products
property of typeDbSet<Product>
public class SampleDbContext : DbContext { public SampleDbContext(string connectionName) : base(connectionName) { } public DbSet<Product> Products { get; set; } }
-
-
Add a SampleDbContextFactory class to the Contexts folder.
-
Implement IDbContextFactory
-
Return a new SampleDbContext in the Create method
-
Specify a connection string for the SampleDb database
class SampleDbContextFactory : IDbContextFactory<SampleDbContext> { public SampleDbContext Create() { return new SampleDbContext(@"Server=(localdb)\mssqllocaldb;Database=SampleDb;Trusted_Connection=True;MultipleActiveResultSets=true"); } }
-
-
In Package Manager Console select the class library project
-
Run the following command:
Enable-Migrations
-
Add code to the
Seed
method in theConfiguration
class in the Migrations foldercontext.Products.AddOrUpdate( new Product { Id = 1, ProductName = "Chai", UnitPrice = 10 }, new Product { Id = 2, ProductName = "Chang", UnitPrice = 11 }, new Product { Id = 3, ProductName = "Aniseed Syrup", UnitPrice = 12 } );
-
Run the
Add-Migration Initial
command -
Run the
Update-Database
command -
Add a data connection to the Server Explorer
-
Verify that the SampleDb database exists and that the Products table contains data
-
-
Add a new Web project to the solution.
- Select .NET Core, ASP.NET Core Web Application
- Select Web API targeting the full .NET Framework
- Set the web project as the startup project for the solution
- Add the EF6 Nuget package to the web project
- Add a project reference to the Data class library project
- Build the solution.
-
Open appsettings.json in the Web project and add the connection string
"ConnectionStrings": { "SampleDb": "Server=(localdb)\\mssqllocaldb;Database=SampleDb;Trusted_Connection=True;MultipleActiveResultSets=true" }
-
In the Web project register the context for DI in Startup.cs.
-
Add following code after
services.AddMvc()
in theConfigureServices
methodservices.AddScoped(provider => { var connectionString = Configuration.GetConnectionString("SampleDb"); return new SampleDbContext(connectionString); });
-
-
Add a
ProductsController
that extendsController
-
Pass
SampleDbContext
to the ctor -
Add actions for GET, POST, PUT and DELETE
[Route("api/[controller]")] public class ProductsController : Controller { private readonly SampleDbContext _dbContext; public ProductsController(SampleDbContext dbContext) { _dbContext = dbContext; } // GET: api/products [HttpGet] public async Task<ActionResult> Get() { var products = await _dbContext.Products .OrderBy(e => e.ProductName) .ToListAsync(); return Ok(products); } // GET api/products/5 [HttpGet("{id}")] public async Task<ActionResult> Get(int id) { var product = await _dbContext.Products .SingleOrDefaultAsync(e => e.Id == id); if (product == null) return NotFound(); return Ok(product); } // POST api/products [HttpPost] public async Task<ActionResult> Post([FromBody]Product product) { _dbContext.Entry(product).State = EntityState.Added; await _dbContext.SaveChangesAsync(); return CreatedAtAction("Get", new { id = product.Id }, product); } // PUT api/products [HttpPut] public async Task<ActionResult> Put([FromBody]Product product) { _dbContext.Entry(product).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); return Ok(product); } // DELETE api/products/5 [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { var product = await _dbContext.Products .SingleOrDefaultAsync(e => e.Id == id); if (product == null) return Ok(); _dbContext.Entry(product).State = EntityState.Deleted; await _dbContext.SaveChangesAsync(); return Ok(); } }
-
-
Test the controller by running the app and submitting some requests.
-
Use Postman or Fiddler
-
Set Content-Type header to application/json for POST and PUT.
-
The database should be created automatically
GET: http://localhost:50781/api/products POST: http://localhost:50781/api/products - Body: {"productName":"Ikura","unitPrice":12} GET: http://localhost:50781/api/products/4 PUT: http://localhost:50781/api/products/4 - Body: {"id":4,"productName":"Ikura","unitPrice":13} DELETE: http://localhost:50781/api/products/4
-
-
Notifications
You must be signed in to change notification settings - Fork 4
Using Entity Framework 6 with ASP.NET Core 2.0
License
tonysneed/Demo.AspNetCore2.EF6
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
About
Using Entity Framework 6 with ASP.NET Core 2.0
Resources
License
Stars
Watchers
Forks
Releases
No releases published
Packages 0
No packages published