Base article
This article is going to handle the connection of an existing website to a local database using the entity framework Core. So, the starting point is going to be the following article:
What is Entity Framework Core?
EF Core is a lightweight, extensible, and cross-platform version of Entity Framework Read more about Entity Framework Core.
Benefits of using Entity Framework Core
- Faster database setup
- Easier to access data, reducing time to read and access data
- Work directly with your complex objects, not with datasets/data tables
- Less code, more control
- No need to write queries, we use LINQ for Entities
Entity Framework vs Entity Framework Core
Entity Framework
- Runs only on Windows
- Can be used with .Net Framework
- No more new features will be added here
Entity Framework Core
- Is Cross-platform, so is not executable only on Windows
- Can be used with .Net Core or .Net Framework
- Keeps growing and getting better every day
Here we have a full comparison of functionalities between both.
Related articles
CRUD Implementation Step-by-Step
Adjust the model in order to make it able to be stored in a database,
public class ValueSamples
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
Create your DB context file
This is the class that is going to connect to your database, each object declared inside the DbSet type is going to be a table.
public class CrudSampleContext : DbContext
{
public CrudSampleContext(DbContextOptions<CrudSampleContext> options) : base(options)
{
}
public DbSet<ValueSamples> ValueSamples { get; set; }
}
Adjust your StartUp class
You must register and initialize your DB context using dependency injection.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<CrudSampleContext>(options => options.UseSqlServer("your database connection string"));
// Register Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Sample API", Version = "version 1" });
});
}
Getting your database connection string
- Open Server Explorer and click on "Connect to Database".
- Select Microsoft SQL Server.
- Pick up your server name and push OK.
- Check the result.
- Right-click on your newly added Data Connection and go to properties.
- Get your connection string.
- Your final Start Up class
With your connection string, your StartUp should look like this.
The items in yellow were added from the connection string above.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<CrudSampleContext>(options => options.UseSqlServer(@"Data Source=yourServer;Integrated Security=True;Database=CRUDSample"));
// Register Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Sample API", Version = "version 1" });
});
}
// 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();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
app.UseMvc();
}
}
Create your database
- Add initial migration
Open your Package Manager Console (PMC) and create your initial migration.
- Check the new folder in your project solution.
- Create the database
Run the command update-database
Check your new Database in your SQL Server Management Studio
CRUD Samples
Remember, to access your API through Swagger you must go to the Swagger endpoint. In my case, it is http://localhost:61986/swagger/index.html
Update your controller actions
- Get
- Create
- Update
- Delete
- Single Get
Your controller must look like this.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly CrudSampleContext _crudSampleContext;
public ValuesController(CrudSampleContext crudSampleContext)
{
this._crudSampleContext = crudSampleContext;
}
// GET api/values
[HttpGet]
public ActionResult<List<ValueSamples>> Get()
{
var itemLst = _crudSampleContext.ValueSamples.ToList();
return new List<ValueSamples>(itemLst);
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
var itemToReturn = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();
return itemToReturn.Name;
}
// POST api/values
[HttpPost]
public void Post([FromBody] ValueSamples createSample)
{
_crudSampleContext.ValueSamples.Add(createSample);
_crudSampleContext.SaveChanges();
}
// PUT api/values/5
[HttpPut]
public void Put([FromBody] ValueSamples updateSample)
{
_crudSampleContext.ValueSamples.Update(updateSample);
_crudSampleContext.SaveChanges();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
var itemToDelete = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();
_crudSampleContext.ValueSamples.Remove(itemToDelete);
_crudSampleContext.SaveChanges();
}
}
Congratulations, you have successfully implemented your CRUD using Entity Framework Core.
External References