DEV Community

Anna
Anna

Posted on • Updated on

Configuring Entity Framework Core into Asp.Net Core

Today I'm going to show you how to create configure project with ASP.Net core, Entity framework core and SQLite.

When I was doing this for the first time it was really difficult for me to understand and in my opinion there are not much tutorials end-to-end tutorials on this topic.

Let's say we have a e-commerce website with products, shopping carts, customers and etc. Let's create models that will transfer the data from our back-end to front-end and entities that will transfer the data from our back-end to database.

Here is the example of model and entity, representing product:

public class ProductModel
    {
        public Guid Id { get; set; }

        public string Description { get; set; }

        public List<ProductPictureModel> ProductPictures { get; set; }

        public CurrencyEnum Currency { get; set; }

        public ProductTypeColorEnum Color { get; set; }

        public decimal Price { get; set; }

        public ProductTypeEnum Type { get; set; }

        public ProductTypeSizeEnum Size { get; set; }

        public bool AvailableInWarehouse { get; set; }
    }
    public class ProductEntity
    {
        public Guid Id { get; set; }

        public string Description { get; set; }

        public virtual ICollection<ProductPictureEntity> ProductPictures { get; set; }

        public CurrencyEnum Currency { get; set; }

        public ProductTypeColorEnum Color { get; set; }

        public decimal Price { get; set; }

        public ProductTypeEnum Type { get; set; }

        public ProductTypeSizeEnum Size { get; set; }

        public virtual ICollection<TagsEntity> Tags { get; set; }

        public bool AvailableInWarehouse { get; set; }

        public DateTime RegistrationDate { get; set; }

        public DateTime LastModified { get; set; }

        public ProductStatusEnum Status { get; set; }
    }

Note that the product model and entity can be different, in our case entity has some additional fields that have nothing to do with the front-end (product status, registration date, last modified) thus with end user. Here is an example of usage of models and entities:

        public async Task<IActionResult> SaveProduct([FromBody]ProductModel product, CancellationToken cancellationToken = default)
        {
            var productEntity = new ProductEntity();
            productEntity = _mapper.Map<ProductModel, ProductEntity>(product);
            productEntity.Status = ProductStatusEnum.Draft;
            productEntity.AdministratorId = Guid.NewGuid();
            productEntity.RegistrationDate = DateTime.Now;
            productEntity.LastModified = DateTime.Now;
            _dbContext.Products.Add(productEntity);
            await _dbContext.SaveChangesAsync(cancellationToken);
            return Ok(productEntity.Id);
        }

Entity framework core is the ORM that works with asp.net core keeping the database scheme in sync with your source code. Here are some basic things that you need to know about EF core:

  • it helps you to create the database tables and relations based on your entities,
  • it automatically tracks the changes that have been done to the entity when you request it from the database.

Start configuring the EF core by creating an ApplicationDbContext class that will represent our database.

public class ApplicationDbContext : DbContext
{
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
     : base(options)
     {
     }


}

Here's what's happening:

  • EF core should recognize our projects database scheme, to do that we need to derive ApplicationDbContext class from EF core's DbContext class.
  • DbContext is a class implemented with Repository pattern that makes it easier to build and query the database and also track the changes in the entities.

Now we need to provide our database credentials and location via connection string so EF Core can connect to database engine. For this we're injecting Asp.net core IConfiguration interface into ApplicationDbContext to get the connection string from configurations in appsettings.json file. Next we need to override OnConfiguring() virtual function, where we also will mention that our engine is SQLite.


private IConfiguration _config;

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IConfiguration config)
            : base(options)
        {
            _config = config;
        }


protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{           
      optionsBuilder
        .UseSqlite(_config.GetConnectionString("DefaultConnection"));

      base.OnConfiguring(optionsBuilder); 
}

Now we have to tell EF core about our entities. For that we will use DbSet generic class, and we will add a new property Products.

public class ApplicationDbContext : DbContext
{
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
     : base(options)
     {
     }

     public DbSet<ProductEntity> Products { get; set; } 

}

This tells EF core to create a new table Products with columns corresponding to fields in ProductEntity class.

Now we need to tell the EF core to configure relation between entities. For that we will override a virtual function OnModelCreating().

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<ProductEntity>()
              .HasMany(p => p.ProductPictures)
              .WithOne();
}

If we look at our ProductEntity class we can see that there's a field ProductPictures, which is an ICollection. In our case we have single product that can have a lot of pictures, database can't store multiple values in single cell, and if you try to store them you'll get and error.

And lastly we need to inject our ApplicationDbContext into Startup.cs:

public void ConfigureServices(IServiceCollection services)
{            
    services.AddDbContext<ApplicationDbContext>();
}

Now we can inject ApplicationDbContext into controllers and query database via.

Hope this will be useful for beginners!

Top comments (1)

Collapse
 
hamidkulachi profile image
Hamidkulachi

Good Artical