Oracle (edit)
The ADO.NET provider with invariant name 'Oracle.ManagedDataAccess.Client' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details
Solution: I resolved this by adding ODP.NET (Oracle.ManagedDataAccess.EntityFramework 12c) from NuGet. I'm running VS2015 with EF 6.2.0.
Oracle Dapper C# : Problem with Kanji characters (Oracle database in Japanese)
C# - How to save unicode data to oracle? - Stack Overflow
ASP.NET - Why are my Chinese characters not displayed correctly in c# string - Stack Overflow
C# - OdbcConnection returning Chinese Characters as "?" - Stack Overflow
C#: DbType.String versus DbType.AnsiString - Stack Overflow
C#/Oracle: Specify Encoding/Character Set of Query? - Stack Overflow
Oracle database: Unicode Database and Unicode Datatype
Ký tự hán tự (kanji character): 鄭 瑋萱
Supporting Multilingual Databases with Unicode (oracle.com)
//INSERT WITH PARAMETER BINDING - UNICODE SAVED
using (System.Data.OracleClient.OracleConnection cn = new System.Data.OracleClient.OracleConnection(connString))
{
cn.Open();
System.Data.OracleClient.OracleCommand cmd = new System.Data.OracleClient.OracleCommand("insert into kuku (kuku) values(:UnicodeString)", cn);
cmd.Parameters.Add(":UnicodeString", System.Data.OracleClient.OracleType.NVarChar).Value = input + " OK" ;
cmd.ExecuteNonQuery();
cn.Close();
}
//FETCH RESULT
using (System.Data.OracleClient.OracleConnection cn = new System.Data.OracleClient.OracleConnection(connString))
{
cn.Open();
System.Data.OracleClient.OracleCommand cmd = new System.Data.OracleClient.OracleCommand("select kuku from kuku", cn);
System.Data.OracleClient.OracleDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
string output = (string) dr[0];
char sa = output[0];
}
cn.Close();
}
Oracle With Dapper
DIPSAS/Dapper.Oracle: Oracle support for Dapper Micro ORM. (github.com)
https://aspnetmaker.dev/ (Code Generate: ASP.NET Maker)
Oracle Managed ODP.NET | Vijay Ganesh (BASIC)
Connect to Oracle database from .NET core application
Oracle Design Basics (haw-hamburg.de)
Oracle/dotnet-db-samples: .NET code samples for Oracle database developers (github.com)
ASP.NET Core Web API With Oracle Database And Dapper (c-sharpcorner.com)
- NTierOracleIdentityExample.Bll
- NTierOracleIdentityExample.Dll
- NTierOracleIdentityExample.Web
ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 01 | Codementor
ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02 | Codementor
- .NET CORE
- ASP.NET CORE
- ASP.NET MVC
- DESIGN PATTERN
- ORACLE
jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup - CodAffection
Build ASP.NET MVC Project with Oracle Data Base using Entity Framework DB first approach
- Install-Package EntityFramework -Version 6.2.0
- Install-Package EntityFramework.ja -Version 6.2.0
- Oracle.ManagedDataAccess.dll -Version 18.3.0
- Oracle.ManagedDataAccess.EntityFramework.dll -Version 18.3.0
Oracle/dotnet-db-samples: .NET code samples for Oracle database developers (github.com)
Oracle Data Access Components (ODAC) for Windows Downloads
Using ASP.NET with Oracle Database
Connecting ASP.NET with Oracle Database - Doyensys Blog
Oracle .NET and Visual Studio Downloads for Oracle Database
ASP.NET Core Web API with Entity Framework Core - @manhng
CQRS Raw SQL and DDD with Dapper - @manhng
Dapper Extensions with Oracle database - @manhng
Dapper + Object Extensions + Visual Studio Extensions - @manhng
Dapper Generic Repository PostgreSQL - @manhng
Dapper Log4net AutoMapper - @manhng
Work with EFCore Dapper together in the PostgreSQL database - @manhng
.NET Core With Oracle Database Using Dapper - @manhng (HAY HAY HAY)
CRUD Operations In ASP.NET Core-3.1 Using Oracle Database (c-sharpcorner.com) (BASIC)
.NET 5.0 - CRUD API Example and Tutorial | Jason Watmore's Blog
ECRUD (Easy-CRUD)
Dapper.Fast.CRUD
MoonStorm/Dapper.FastCRUD: The fastest micro-orm extension for Dapper (github.com)
Connect application with Oracle Database using entity framework in MVC 5
Here are good example that discus step by step , please following below links:
https://csharp.today/entity-framework-6-database-first-with-oracle/
http://www.codeproject.com/Tips/421105/Using-Oracle-with-EntityFramework
Please following below link, show you CRUD
http://www.codeproject.com/Tips/869553/CRUD-operation-with-Entity-Framework-Database-Fi
http://www.codeproject.com/Articles/812005/ASP-NET-MVC-CRUD-Application-with-drop-down-list
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/crud-operation-in-Asp-Net-mvc-framework/
http://cybarlab.com/crud-operation-in-asp-net-mvc-using-entity-framework
Oracle XE
https://geraldonit.com/2019/08/19/how-to-install-oracle-database-18c-xe-on-windows/
https://blog.toadworld.com/2018/09/26/how-to-install-oracle-database-18c-on-windows/
https://rustamkhodjaev.com/2020/04/28/install_database_express_edition_18c_on_windows/
A WinForms SQL client for generating C# query result classes, Dapper productivity
Note: Only for OleDb, MySql, SqlServer, SqlCe, not for Oracle
HigLabo
Dapper + DapperExtensions + CodeGenerator easy to play sqlserver, mysql, oracle, postgresql, sqlite
ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 01
In this tutorial series we will be creating ASP.NET Core MVC Web application using ORACLE Database. Before we dive into anything, whole code with database scripts will be available on Github.This tutorial series will be split into 3 parts.
First part is setting up our development environment, setting up multiple projects with structure that will use couple of design patterns like N-tier architecture, SOC, Unit of Work and scaffolding existing ORACLE 12.2 database and creating our first migration.
Second part will be explaining our architecture of application, implementing Repository pattern for our Data layer, keeping SoC, implementing base interfaces for CRUD operations on existing database. Then we will create our service or Business logic layer by implementing interfaces that will represent Unit of Work. And last, in our web project we will use model to view model mapping and create our mapping profile.
Third part will be explaining how to use ASP.NET Identity with ORACLE database and with Windows authentication. So lets start shall we?
First things first lets explain what type of project are we going to use and how are we going to connect to database using code first approach of entity framework. Open your Visual Studio (Mine is 2019), then File -> New -> Project.
Next we are going to choose out project type. We will be using ASP.NET Core Web App(Model-View-Controller) type of project.
Then click next and name your project and solution and choose folder. For out N-Tier artchitecture we will be creating three projects. First will be our Web project, Second will be our Business logic layer and last will be Data logic layer. So when creating we will name our Web project with .Web extension. Next two project will have .Bll and .Dll extensions as well.
Next we will use .NET 5.0 as our target framework and will not choose any type of authentication for now, as we will be adding Windows authentication with ASP.NET Identity later. Click create and we are done.
So now we have to add two more projects for our business and data layers. Right click on solution and choose New project.
Choose Class library(not .NET Framework one), and click next. Choose same name of web project but with .Dll and .Bll extensions.
Click Next and choose .NET 5.0 as target framework and last create your project.
We will have structure like on next image.
Next thing that we will do is to setup our Dll project. This will include installing additional packages for connecting to Oracle database, organizing our project with SoC pattern (separation of concerns) and setting up our first migration.
So go to NuGet package manager, either by right clicking on Dll project and choosing “Manage NuGet packages” or opening console. Then browse for next packages and install them:
- Microsoft.EntityFrameworkCore.Design
- Oracle.EntityFrameworkCore
Next we will add a few folders that will structure our application in order to implement our design patterns and organize it properly.
First add next 4 folders:
- Context
- Entities
- Migrations
- Repositories
And in Repositories add Abstract and Implementation folders. These folders will hold our abstract repositories for accessing our data. Context folder will hold our generated Context class, Migrations folder will hold our migrations and Entities will hold our generated classes/models for data access. Project structure should look like this.
Next we will generate our Context class and Entities. Just to mention, we are generating context and entities from existing database, which means that we are scaffolding from existing database. Initially if we did not have already existing database, we would just create those classes and execute our first migration that will create new tables in our database.
First we need to install dotnet cli. For more reference check this official link:
Go to package manager console, choose .Dll project and execute this command:
So, now we will generate our context and entity classes from our existing database schema on Oracle 12c release 2 (12.2). To do that we need to use dotnet ef command with specifying of couple parameters:
-o tells us what output directory of our Dll project will entities be placed in. In our case it is Entities
- -context-dir tells us what output directory of our Dll project will context be placet. In our case it is Context folder
-c tells what will be name of our
-p tells us on what project command will execute. In our case it id Dll project
-f tells us that we do not need to confirm our scaffolding
Whole command should look like this:
dotnet ef dbcontext scaffold "User Id=EXAMPLE_SCHEMA;Password=my_password;Data Source=server:1521/orcl;Connection Timeout=600;min pool size=0;connection lifetime=18000;PERSIST SECURITY INFO=True;" Oracle.EntityFrameworkCore -o Entities --context-dir Context -c EXAMPLE_SCHEMA_Context -f -p NTierOracleIdentityExmple.Dll
After we execute command we will generate context class, entities and migration in our folders that we have created.
Also there is a shortcut to dotnet ef and that is EF Core Power Tools that can be found on next link.
It can be installed as and VS2019 extension that can generate needed stuff either by scaffolding existing DB using code first or database first approach(create edmx file) and can generate migrations for existing code.
So lets assume that we have our schema already created in our database with some tables in it. So it might look like this.
After execution of previous command, our project should include next generated classes for our context and existing entities.
Next thing is to modify our Context. First install next package from NuGet:
- Microsoft.EntityFrameworkCore.Proxies
https://stackoverflow.com/questions/55234943/what-is-the-equivalent-of-configuration-proxycreationenabled-in-ef-core
Next modify OnConfiguring method in context and add next line that contain our connection string:
if (!optionsBuilder.IsConfigured) { //Proxy for navigation properties //Microsoft.EntityFrameworkCore.Proxies optionsBuilder.UseLazyLoadingProxies().UseOracle(“User Id=SCHEMA_NAME;Password=xxxxx;Data Source=server:1521/SID;Connection Timeout=600;min pool size=0;connection lifetime=18000;PERSIST SECURITY INFO=True;”); }
First our edit contains connection string that will be used from our context to connect and create/apply new migrations. Second change is change that is using UseLazyLoadingProxies that includes navigational properties from our context entities that we select. This is explained in next Stackoverflow question.
Our last change will include changing the OnModelCreating method. Add next line:
base.OnModelCreating(modelBuilder);
Now we are ready to create our first migration. Our first migration will include only one table that will represent our log table for logging data from our application. Later in next part we will create repository, service and controller actions for implementing CRUD functionalities over that table. Also we will create our CRUD functionalities over Identity table in part 3.
So first things first, lets define our table. Create next class in Entities folder of our DLL project.
public class Log { public int pk { get; set; } public string CreatedBy { get; set; } public DateTime CreationDate { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } public DateTime? Date { get; set; } public string Value { get; set; } }
Next thing is to create how our table is going to look when we create it in Oracle database schema. Open Context class from Context folder of our DLL project.
First add our table as DbSet.
public virtual DbSet<Log> Log{ get; set; }
Next is to define how our table is going to look when our context class build our entity. Add next code to OnModelCreating method.
modelBuilder.Entity<Log>(entity => { entity.HasKey(e => e.pk).HasName("LOG_PK"); entity.ToTable("LOG"); entity.Property(e => e.pk) .HasColumnType("NUMBER(10)") .HasColumnName("PK"); entity.Property(e => e.CreatedBy) .HasMaxLength(256) .IsUnicode(false) .HasColumnName("CREATED_BY"); entity.Property(e => e.CreationDate) .HasColumnType("DATE") .HasColumnName("CREATION_DATE"); entity.Property(e => e.ModifiedBy) .HasMaxLength(256) .IsUnicode(false) .HasColumnName("MODIFIED_BY"); entity.Property(e => e.ModifiedDate) .HasColumnType("DATE") .HasColumnName("MODIFIED_DATE"); entity.Property(e => e.Value) .IsUnicode(false) .HasColumnName("LOG_VALUE"); });
Only thing remaining is to create our first migration and update database. Lets create our DATA_LOG migration.
dotnet ef migrations add EXAMPLE_SCHEMA_LOG -p NTierOracleIdentityExmple.Dll -c NTierOracleIdentityExample.Dll.Context.EXAMPLE_SCHEMA_Context -o Migrations
After executing this command, our migration class will be created in Migrations folder of our DLL project.
Now lets update our database
dotnet ef database update EXAMPLE_SCHEMA_LOG -p NTierOracleIdentityExmple.Dll -c NTierOracleIdentityExample.Dll.Context.EXAMPLE_SCHEMA_Context
Now if you open the Oracle database from any client tool like SQLDeveloper or Toad you will see our table created, with migration history table.
That is it for now. Next part will be explaining how to create base repository, services for our CRUD operations with couple of design patterns.iting here...
ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02
In this part of our tutorial, we will dive into creating basic project structure for N-tier project including creating base repository and creating data layer, creating service layer and using all of newly created stuff in our Web project.
First things first, in previous part we have created our context with entities, explained how to create migration (code first approach) with Oracle database using EFCore and how to scaffold existing database entities into our project (database first approach). Now we will put everything in use through couple of design patterns in multiple layers.
Data logic layer and Repository Pattern
First pattern that we will implement is Repository pattern in our data-access layer. Our code will create generic IBaseRepository with CRUD operations that contains INSERT, UPDATE, DELETE and SELECT operations and later we are going to add implementation of IBaseRepository.
Entity Framework already implements the repository pattern as we can access, add, modify and delete entities through DbSet. We are creating generic IBaseRepository interface and implementation of that repository to avoid boilerplate code for CRUD operations of every repostory for each entity.
Now lets create generic interface IBaseRepository with basic CRUD operation.
Add IBaseRepository interface class in Repositores/Abstract folder of DLL project:
public interface IBaseRepository<T> where T : class { #region Select methods Task<T> SelectById(int id); Task<List<T>> SelectAll(); #endregion #region Insert methods Task<T> Insert(T entity); #endregion #region Update methods void Update(T entity); #endregion #region Delete methods void Delete(int Id); #endregion #region Other methods void SaveChanges(); #endregion }
The IBaseRepository interface accept one generic type T. T as defined must be a class, so it must be entity just like one from our Entities folder in DLL project. As previously explained our generic IBaseRepository interface is defining base CRUD operations that we will implement later in our BaseRepository implementation. Lets create implementation of our generic IBaseRepository.
Add BaseRepository implementation in Repositores/Implementation folder of DLL project:
public class BaseRepository<T> : IBaseRepository<T> where T : class { #region Fields protected readonly DbContext _context; protected readonly DbSet<T> dbSet; #endregion #region Constructor protected BaseRepository(DbContext context) { _context = context; dbSet = context.Set<T>(); } #endregion #region Select methods public virtual async Task<T> SelectById(int id) { return await dbSet.FindAsync(id); } public virtual async Task<List<T>> SelectAll() { return await dbSet.ToListAsync(); } #endregion #region Insert methods public virtual async Task<T> Insert(T entity) { var addedEntity = (await dbSet.AddAsync(entity)).Entity; await _context.SaveChangesAsync(); return addedEntity; } #endregion #region Update methods public virtual async void Update(T entity) { dbSet.Update(entity); await _context.SaveChangesAsync(); } #endregion #region Delete methods public async void Delete(int Id) { T entity = dbSet.Find(Id); var removedEntity = dbSet.Remove(entity).Entity; await _context.SaveChangesAsync(); } #endregion #region Other methods public void SaveChanges() { _context.SaveChanges(); } #endregion }
Your project structure should look like this.
Now, next step would be for us to implement entity repository for our database entities. In previous chapter we have created two entities: Log and ExampleTable. Lets create interfaces for our entity repositories and implementation of those repositories. First add ILogRepository interface in Repositores/Abstract folder of DLL project:
public interface ILogRepository : IBaseRepository<Log>, IDisposable { //Additional methods or override ones from BaseRepository #region Select methods #endregion #region Insert methods #endregion #region Update methods #endregion #region Delete methods #endregion #region Other methods #endregion }
Next, Add LogRepository implementation in Repositores/Implementation folder of DLL project:
public class LogRepository : BaseRepository<Log>, ILogRepository { //Implement additional methods or override ones from BaseRepository and implement them #region Select methods public LogRepository(EXAMPLE_SCHEMA_Context context) : base(context) { } #endregion #region Select methods #endregion #region Insert methods #endregion #region Update methods #endregion #region Delete methods #endregion #region Other methods public void Dispose() { _context.Dispose(); } #endregion }
Now lets do the same for our second entity ExampleTable. First add IExampleTableRepository interface in Repositores/Abstract folder of DLL project:
public interface IExampleTableRepository : IBaseRepository<ExampleTable>, IDisposable { //Additional methods or override ones from BaseRepository #region Select methods #endregion #region Insert methods #endregion #region Update methods #endregion #region Delete methods #endregion #region Other methods #endregion }
Next, Add ExampleTableRepository implementation in Repositores/Implementation folder of DLL project:
public class ExampleTableRepository : BaseRepository<ExampleTable>, IExampleTableRepository { //Implement additional methods or override ones from BaseRepository and implement them #region Select methods public ExampleTableRepository(EXAMPLE_SCHEMA_Context context) : base(context) { } #endregion #region Select methods #endregion #region Insert methods #endregion #region Update methods #endregion #region Delete methods #endregion #region Other methods public void Dispose() { _context.Dispose(); } #endregion }
As we can see, we are extending BaseRepository in our entity repositories. In ILogRepository or any other interface we can add additional methods that are applicable only for that entity. That is why we are extending LogRepository as BaseRepository and implementing ILogRepository. BaseRepository contains basic CRUD operations and ILogRepository contains entity specific methods, procedures and other LINQ code.
Your project structure should look like this.
Business logic layer and Services
Now that we have implemented the repositories in our DLL project it is time to move to Business logic layer project to implement our services which will implement Unit of Work pattern. Unit of work pattern tracks a business transaction and translate that transaction into database transaction. For example if we have ten steps for our business transaction, and those steps are connected with business logic in some way, we can collectively run that transaction as one unit.
Implementation of Unit of Work pattern should look like this.
So lets create ILogService, IExampleTableServices interfaces and LogService, ExampleTableService as implementation of those interfaces.
public interface ILogService { #region Select methods Task<List<Log>> SelectLog(); Task<Log> SelectLogById(int Id); #endregion #region Insert methods void InsertLog(Log entity); #endregion #region Update methods void UpdateLog(Log entity); #endregion #region Delete methods void DeleteLog(int Id); #endregion } public class LogService : ILogService { //Service can have multiple repositories implementing UoW(Unit oof Work) design pattern. #region Fields private readonly ILogRepository _logRepository; #endregion #region Constructor public LogService(ILogRepository logRepository) { _logRepository = logRepository; } #endregion #region Select methods public Task<List<Log>> SelectLog() { return _logRepository.SelectAll(); } public Task<Log> SelectLogById(int Id) { return _logRepository.SelectById(Id); } #endregion #region Insert methods public void InsertLog(Log entity) { _logRepository.Insert(entity); } #endregion #region Update methods public void UpdateLog(Log entity) { _logRepository.Update(entity); } #endregion #region Delete methods public void DeleteLog(int Id) { _logRepository.Delete(Id); } #endregion #region Other methods #endregion } public interface IExampleTableService { #region Select methods Task<List<ExampleTable>> SelectExampleTable(); Task<ExampleTable> SelectExampleTableById(int Id); #endregion #region Insert methods void InsertExampleTable(ExampleTable entity); #endregion #region Update methods void UpdateExampleTable(ExampleTable entity); #endregion #region Delete methods void DeleteExampleTable(int Id); #endregion } public class ExampleTableService : IExampleTableService { //Service can have multiple repositories implementing UoW(Unit oof Work) design pattern. #region Fields private readonly IExampleTableRepository _exampleTableRepository; #endregion #region Constructor public ExampleTableService(IExampleTableRepository ExampleTableRepository) { _exampleTableRepository = ExampleTableRepository; } #endregion #region Select methods public Task<List<ExampleTable>> SelectExampleTable() { return _exampleTableRepository.SelectAll(); } public Task<ExampleTable> SelectExampleTableById(int Id) { return _exampleTableRepository.SelectById(Id); } #endregion #region Insert methods public void InsertExampleTable(ExampleTable entity) { _exampleTableRepository.Insert(entity); } #endregion #region Update methods public void UpdateExampleTable(ExampleTable entity) { _exampleTableRepository.Update(entity); } #endregion #region Delete methods public void DeleteExampleTable(int Id) { _exampleTableRepository.Delete(Id); } #endregion #region Other methods #endregion }
Our BLL project structure should look like this:
That is it. Unit of work consist of multiple repositories that implement some business logic, incorporating all of them in single service.
Dependency Injection
So what is our next step? Next we are going to use our repositories and services in our controllers. We are going to inject repositories into our services and later those services into our controllers which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. There are multiple libraries that allow us to inject needed dependencies of a class, but we will use standard ASP.NET CORE DI framework for injecting our dependencies.
Before we dive into code, lets explain 3 lifetime modes for service being injected:
Scoped - lifetime services are created once per request within the scope.
Transient - lifetime services are created each time they are requested.
Singleton - which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.
Lets open Startup.cs class and in ConfigureServices method inject our DBContext and needed services and repositories.
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); //Dependency injection services.AddEntityFrameworkOracle().AddDbContext<EXAMPLE_SCHEMA_Cont ext>(); services.AddScoped(typeof(IBaseRepository<>),typeof(BaseRepository<> )); services.AddScoped(typeof(ILogRepository),typeof(LogRepository)); services.AddScoped(typeof(IExampleTableRepository),typeof(ExampleTab leRepository)); }
AutoMapper mapping between DLL entities and ViewModels
Next, problem that we are going to solve is problem of mapping of our DLL entities that are generated either by code first or database first approach. Every time we need to modify our entity we loose DataAnotations and we need to apply that change again, or we need to add new properties to every entity where we are copying data and change our logic for copying one object to another in our code (Entity to EntityViewModel and vice versa).
The AutoMapper in C# is a mapper between two objects. It maps the properties of two different objects by transforming the input object of one type to the output object of another type.
Lets first install AutoMapper either through GUI on our web project by Right Click on Dependencies of Web project and then Manage NuGet Packages
or executing following PM console commands on Web project:
- Install-Package AutoMapper -Version 11.0.0
- Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 11.0.0
Next in our Startup.cs class in ConfigureServices method add next code:
public void ConfigureServices(IServiceCollection services) { … //AutoMapper setup services.AddAutoMapper(typeof(Startup)); … … //Dependency injection services.AddSingleton(provider => new MapperConfiguration(cfg => { cfg.AddProfile(new EXAMPLE_SCHEMA_Profile()); }).CreateMapper()); … }
Next, lets create ViewModel for our Log and ExampleTable entity classes:
public class LogViewModel { public int pk { get; set; } public string CreatedBy { get; set; } public DateTime CreationDate { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } public DateTime? Date { get; set; } public string Value { get; set; } } public class ExampleTableViewModel { public int Pk { get; set; } public string CreatedBy { get; set; } public DateTime CreationDate { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } public string Name { get; set; } }
Next lets create AutoMapperConfigurations folder in NTierOracleIdentityExample.Web project. Then create new profile called EXAMPLE_SCHEMA_Profile class in newly created folder:
public class EXAMPLE_SCHEMA_Profile : Profile { public EXAMPLE_SCHEMA_Profile() { CreateMap<Log, LogViewModel>().ReverseMap(); CreateMap<ExampleTable, ExampleTableViewModel>().ReverseMap(); } }
As you can see from previous code, we need to map each property of entity class to the correspondent ViewModel class using AutoMapper.
Note: When the property names are different in Source and Destination types, then by default the C# Automapper will not map those properties.
Our Web project structure should look like this:
Wrapping up Controller
Last, lets add some code to our HomeController. We will inject ILogService and IMapper interfaces in contructor of HomeController. Next we will add some dummy methods for CRUD operations of our service, like GetLog, GetLogById, EditLog and DeleteLog.
public class HomeController : Controller { #region Fields private readonly IMapper _mapper; private readonly ILogService _logService; #endregion #region Constructor public HomeController(ILogService logService, IMapper mapper) { _logService = logService; _mapper = mapper; } #endregion #region GET methods public IActionResult Index() { return View(); } public JsonResult GetLog() { List<LogViewModel> logs = _mapper.Map<List<Log>, List<LogViewModel>>(_logService.SelectLog().Result); var logList = from l in logs select new { Id = l.pk, LogDate = l.Date, LogValue = l.Value }; return Json(new { status = “success”, records = logList.OrderBy(l => l.Id).ToList(), total = logList.Count() }); } public JsonResult GetLogById(int pk) { LogViewModel log = _mapper.Map<Log, LogViewModel>(_logService.SelectLogById(pk).Result); return Json(new { status = “success”, records = log }); } #endregion #region POST methods [HttpPost] public JsonResult EditLog(LogViewModel viewModel) { if (ModelState.IsValid) { //Map viewModel to model Log model = _mapper.Map<Log>(viewModel); model.ModifiedBy = “DummyUser”; model.ModifiedDate = DateTime.Now; _logService.UpdateLog(model); return Json(new { success = true, message = “Log saved!” }); } else { return Json(new { success = false, message = “Error!” }); } } [HttpPost] public JsonResult DeleteLog(int pk) { _logService.DeleteLog(pk); return Json(new { success = false, message = “Log deleted!” }); } #endregion #region Helper methods #endregion }
So, that is it for this part. In next part we will cover the ASP.NET Identity with ORACLE database and how to create needed entities in database for Identity and how to implement it in our application. And finally run our application.