step1 : Create your project with MVC and webapi
add connection string
<connectionStrings>
<add name="OesV1DbContext" connectionString="Data Source=abc;Persist Security Info=true;Initial Catalog=MyTestDb; User ID=sa;Password=pwd; Integrated Security=false;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
----------------------------------------------------------------------------------
step2 : add class library:
and 1 class file and add following code:
public class OesV1DbContext : DbContext
{
public OesV1DbContext() : base("OesV1DbContext")
{
Database.SetInitializer<OesV1DbContext>(null);
}
public DbSet<User> UserEntities { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
-------------------------------------------------------------------------------
step3 :add one more class and following code
public class OesV1DbContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<OesV1DbContext>
{
protected override void Seed(OesV1DbContext context)
{
// with empty database
}
}
-----------------------------------------------------------------------
step4 : add following class for database
class0
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
}
Class1
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public int Age { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
class 2
public enum Grade { A, B, C, D, F }
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
class3
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
-------------------------------------------------------------------
step4 : add folder in class library
then add interface and its implementation
// interface
public interface IUserRepository
{
IQueryable<User> GetAllUsers();
IQueryable<User> GetUserById(int userId);
int AddUser(User user);
int UpdateUser(User user);
bool DeleteUser(int userId);
}
-----------------------------------------------------
// implementation
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Infrastructure;
namespace OesRepo1.Reprository
{
public class UserRepository : IUserRepository
{
private OesV1DbContext dbContext = new OesV1DbContext();
public int AddUser(User user)
{
dbContext.UserEntities.Add(user);
dbContext.SaveChanges();
return user.UserId;
}
public bool DeleteUser(int userId)
{
User user = dbContext.UserEntities.Find(userId);
if (user == null)
{
return false;
}
dbContext.UserEntities.Remove(user);
dbContext.SaveChanges();
return true;
}
public IQueryable<User> GetAllUsers()
{
var result = dbContext.UserEntities;
return result;
}
public IQueryable<User> GetUserById(int userId)
{
var result = dbContext.UserEntities.Where(x => x.UserId == userId);
return result;
}
public int UpdateUser(User user)
{
if (UserExists(user.UserId))
{
dbContext.Entry(user).State = EntityState.Modified;
try
{
dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
throw ex;
}
}
return user.UserId;
}
private bool UserExists(int id)
{
return dbContext.UserEntities.Count(e => e.UserId == id) > 0;
}
}
}
/////////////////////
Create controller and add following code
using OesRepo1;
using OesRepo1.Reprository;
using OesV1.Attributes;
using OesV1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
namespace OesV1.Controllers
{
[RoutePrefix("api/user")]
public class UserController : ApiController
{
private readonly IUserRepository _userRepository;// = new UserRepository();
// constructor dependency injection
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
// GET: api/user/getallusers
/// <summary>
/// Get all users from Db
/// </summary>
/// <returns>UserApiModel</returns>
[HttpGet]
//[APIAuthenticationFilter(true)]
[ResponseType(typeof(List<UserApiModel>))]
[Route("getallusers")]
public async Task<IHttpActionResult> GetUsers()
{
var result = _userRepository.GetAllUsers();
if (result == null)
{
return NotFound();
}
var userList = MapUser(result);
return Ok(userList);
}
// GET: api/user/1
/// <summary>
/// Get User by Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
//[APIAuthenticationFilter(true)]
[ResponseType(typeof(UserApiModel))]
[Route("getuserbyid/{id}")]
public async Task<IHttpActionResult> GetUser(int id)
{
var result = _userRepository.GetUserById(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
/// <summary>
/// Add user in database
/// </summary>
/// <param name="userApiModel"></param>
/// <returns></returns>
[HttpPost]
[Route("adduser")]
public async Task<IHttpActionResult> AddUser(UserApiModel userApiModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User dbUser = new User
{
UserName = userApiModel.UserName,
Password = userApiModel.Password,
DisplayName=userApiModel.Name
};
var userId = _userRepository.AddUser(dbUser);
if (userId == 0)
{
return NotFound();
}
return Ok(userId);
//return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
}
[HttpPut]
[Route("updateuser")]
public async Task<IHttpActionResult> UpdateUser(UserApiModel userApiModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User dbUser = new User
{
UserId=userApiModel.UserId,
UserName = userApiModel.UserName,
Password = userApiModel.Password,
DisplayName = userApiModel.Name
};
var userId = _userRepository.UpdateUser(dbUser);
if (userId == 0)
{
return NotFound();
}
return Ok(userId);
//return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
}
/// <summary>
/// Delete user by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete]
[Route("deleteuser/{id}")]
public async Task<IHttpActionResult> DeleteStudent(int id)
{
var result = _userRepository.DeleteUser(id);
if (!result)
{
return NotFound();
}
return Ok(result);
}
#region private section
private List<UserApiModel> MapUser(IQueryable<User> result)
{
List<UserApiModel> userList = new List<UserApiModel>();
foreach (var item in result)
{
UserApiModel userObject = new UserApiModel
{
UserId = item.UserId,
UserName = item.UserName,
Password = item.Password,
Name = item.DisplayName
};
userList.Add(userObject);
}
return userList;
}
#endregion
}
}
/////////////////////////////////
I have implemented structure map dependency injection so you can also add.
and in default registry you can add following code
//For<IExample>().Use<Example>();
For<IUserRepository>().Use<UserRepository>();
add connection string
<connectionStrings>
<add name="OesV1DbContext" connectionString="Data Source=abc;Persist Security Info=true;Initial Catalog=MyTestDb; User ID=sa;Password=pwd; Integrated Security=false;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
----------------------------------------------------------------------------------
step2 : add class library:
and 1 class file and add following code:
public class OesV1DbContext : DbContext
{
public OesV1DbContext() : base("OesV1DbContext")
{
Database.SetInitializer<OesV1DbContext>(null);
}
public DbSet<User> UserEntities { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
-------------------------------------------------------------------------------
step3 :add one more class and following code
public class OesV1DbContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<OesV1DbContext>
{
protected override void Seed(OesV1DbContext context)
{
// with empty database
}
}
-----------------------------------------------------------------------
step4 : add following class for database
class0
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
}
Class1
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public int Age { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
class 2
public enum Grade { A, B, C, D, F }
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
class3
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
-------------------------------------------------------------------
step4 : add folder in class library
then add interface and its implementation
// interface
public interface IUserRepository
{
IQueryable<User> GetAllUsers();
IQueryable<User> GetUserById(int userId);
int AddUser(User user);
int UpdateUser(User user);
bool DeleteUser(int userId);
}
-----------------------------------------------------
// implementation
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Infrastructure;
namespace OesRepo1.Reprository
{
public class UserRepository : IUserRepository
{
private OesV1DbContext dbContext = new OesV1DbContext();
public int AddUser(User user)
{
dbContext.UserEntities.Add(user);
dbContext.SaveChanges();
return user.UserId;
}
public bool DeleteUser(int userId)
{
User user = dbContext.UserEntities.Find(userId);
if (user == null)
{
return false;
}
dbContext.UserEntities.Remove(user);
dbContext.SaveChanges();
return true;
}
public IQueryable<User> GetAllUsers()
{
var result = dbContext.UserEntities;
return result;
}
public IQueryable<User> GetUserById(int userId)
{
var result = dbContext.UserEntities.Where(x => x.UserId == userId);
return result;
}
public int UpdateUser(User user)
{
if (UserExists(user.UserId))
{
dbContext.Entry(user).State = EntityState.Modified;
try
{
dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
throw ex;
}
}
return user.UserId;
}
private bool UserExists(int id)
{
return dbContext.UserEntities.Count(e => e.UserId == id) > 0;
}
}
}
/////////////////////
Create controller and add following code
using OesRepo1;
using OesRepo1.Reprository;
using OesV1.Attributes;
using OesV1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
namespace OesV1.Controllers
{
[RoutePrefix("api/user")]
public class UserController : ApiController
{
private readonly IUserRepository _userRepository;// = new UserRepository();
// constructor dependency injection
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
// GET: api/user/getallusers
/// <summary>
/// Get all users from Db
/// </summary>
/// <returns>UserApiModel</returns>
[HttpGet]
//[APIAuthenticationFilter(true)]
[ResponseType(typeof(List<UserApiModel>))]
[Route("getallusers")]
public async Task<IHttpActionResult> GetUsers()
{
var result = _userRepository.GetAllUsers();
if (result == null)
{
return NotFound();
}
var userList = MapUser(result);
return Ok(userList);
}
// GET: api/user/1
/// <summary>
/// Get User by Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
//[APIAuthenticationFilter(true)]
[ResponseType(typeof(UserApiModel))]
[Route("getuserbyid/{id}")]
public async Task<IHttpActionResult> GetUser(int id)
{
var result = _userRepository.GetUserById(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
/// <summary>
/// Add user in database
/// </summary>
/// <param name="userApiModel"></param>
/// <returns></returns>
[HttpPost]
[Route("adduser")]
public async Task<IHttpActionResult> AddUser(UserApiModel userApiModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User dbUser = new User
{
UserName = userApiModel.UserName,
Password = userApiModel.Password,
DisplayName=userApiModel.Name
};
var userId = _userRepository.AddUser(dbUser);
if (userId == 0)
{
return NotFound();
}
return Ok(userId);
//return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
}
[HttpPut]
[Route("updateuser")]
public async Task<IHttpActionResult> UpdateUser(UserApiModel userApiModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User dbUser = new User
{
UserId=userApiModel.UserId,
UserName = userApiModel.UserName,
Password = userApiModel.Password,
DisplayName = userApiModel.Name
};
var userId = _userRepository.UpdateUser(dbUser);
if (userId == 0)
{
return NotFound();
}
return Ok(userId);
//return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
}
/// <summary>
/// Delete user by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete]
[Route("deleteuser/{id}")]
public async Task<IHttpActionResult> DeleteStudent(int id)
{
var result = _userRepository.DeleteUser(id);
if (!result)
{
return NotFound();
}
return Ok(result);
}
#region private section
private List<UserApiModel> MapUser(IQueryable<User> result)
{
List<UserApiModel> userList = new List<UserApiModel>();
foreach (var item in result)
{
UserApiModel userObject = new UserApiModel
{
UserId = item.UserId,
UserName = item.UserName,
Password = item.Password,
Name = item.DisplayName
};
userList.Add(userObject);
}
return userList;
}
#endregion
}
}
/////////////////////////////////
I have implemented structure map dependency injection so you can also add.
and in default registry you can add following code
//For<IExample>().Use<Example>();
For<IUserRepository>().Use<UserRepository>();