What should I implement to inset multiple Students in database? - database

In this, I have implemented a .Net Core web API where I have two model classes Student and Department.
I have implemented One to One relationship between these two entities. There are two controllers StudentController and DepartmentController. Student model has reference of Department entity and has DepartmentId as foreign key. Each student is assigned to a department. What implementation is required to perform multiple Students entry in database and how to check the same implementation in Postman?
How to create endpoint to add multiple students using JSON format without ViewModel?
Student.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Students.Models
{
public class Student
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SId { get; set; }
[Required]
[Column(TypeName ="varchar(50)")]
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
}
Department.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Students.Models
{
public class Department
{
[Key]
public int Id { get; set; }
[Required]
[Column(TypeName = "varchar(20)")]
public string Dep { get; set; }
}
}
DepartmentController.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Students.Models;
namespace Students.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DepartmentController : ControllerBase
{
private readonly StudentContext _context;
public DepartmentController(StudentContext context)
{
_context = context;
}
// GET: api/Department
[HttpGet]
public async Task<ActionResult<IEnumerable<Department>>> GetDepartments()
{
return await _context.Departments.ToListAsync();
}
// GET: api/Department/5
[HttpGet("{id}")]
public async Task<ActionResult<Department>> GetDepartment(int id)
{
var department = await _context.Departments.FindAsync(id);
if (department == null)
{
return NotFound();
}
return department;
}
// PUT: api/Department/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutDepartment(int id, Department department)
{
if (id != department.Id)
{
return BadRequest();
}
_context.Entry(department).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DepartmentExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok();
}
// POST: api/Department
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Department>> PostDepartment(Department department)
{
_context.Departments.Add(department);
await _context.SaveChangesAsync();
return CreatedAtAction("GetDepartment", new { id = department.Id }, department);
}
// DELETE: api/Department/5
[HttpDelete("{id}")]
public async Task<ActionResult<Department>> DeleteDepartment(int id)
{
var department = await _context.Departments.FindAsync(id);
if (department == null)
{
return NotFound();
}
_context.Departments.Remove(department);
await _context.SaveChangesAsync();
return department;
}
private bool DepartmentExists(int id)
{
return _context.Departments.Any(e => e.Id == id);
}
}
}
StudentsController.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Students.Models;
namespace Students.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly StudentContext _context;
public StudentsController(StudentContext context)
{
_context = context;
}
// GET: api/Students
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
return await _context.Students.Include(d => d.Department).ToListAsync();
}
// GET: api/Students/5
[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetStudent(int id)
{
var student = await _context.Students.Include(d => d.Department).FirstOrDefaultAsync(i => i.SId == id);
if (student == null)
{
return NotFound();
}
return student;
}
// PUT: api/Students/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutStudent(int id, Student student)
{
if (id != student.SId)
{
return BadRequest();
}
_context.Departments.Update(student.Department);
await _context.SaveChangesAsync();
_context.Entry(student).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok();
}
// POST: api/Students
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Student>> PostStudent(Student student)
{
//_context.Departments.Add(student.Department);
//await _context.SaveChangesAsync();
_context.Students.Add(student);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStudent", new { id = student.SId }, student);
}
// DELETE: api/Students/5
[HttpDelete("{id}")]
public async Task<ActionResult<Student>> DeleteStudent(int id)
{
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return student;
}
private bool StudentExists(int id)
{
return _context.Students.Any(e => e.SId == id);
}
}
}
StudentContext.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Students.Models
{
public class StudentContext:DbContext
{
public StudentContext(DbContextOptions<StudentContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
}
}
StudentContextModelSnapshot.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Students.Models;
namespace Students.Migrations
{
[DbContext(typeof(StudentContext))]
partial class StudentContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Students.Models.Department", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Dep")
.IsRequired()
.HasColumnType("varchar(20)");
b.HasKey("Id");
b.ToTable("Departments");
});
modelBuilder.Entity("Students.Models.Student", b =>
{
b.Property<int>("SId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("DepartmentId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(50)");
b.HasKey("SId");
b.HasIndex("DepartmentId");
b.ToTable("Students");
});
modelBuilder.Entity("Students.Models.Student", b =>
{
b.HasOne("Students.Models.Department", "Department")
.WithMany()
.HasForeignKey("DepartmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

What implementation is required to perform multiple Students entry in database and how to check the same implementation in Postman?
You could add PostStudentList method like below :
[HttpPost]
[Route("StudentList")]
public async Task<ActionResult<Student>> PostStudentList([FromForm] List<Student> student)
{
_context.Students.AddRange(student);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStudents", student);
}
Use Postman to send the list of students with form-data contentType
Updated ,send entries in JSON format
PostStudentList method :
public class StudentVM
{
public List<Student> student { get; set; }
}
[HttpPost]
[Route("StudentList")]
public async Task<ActionResult<Student>> PostStudentList(StudentVM model)
{
var students = new List<Student>();
students = model.student;
_context.Students.AddRange(students);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStudents", students);
}
Postman:

Related

Join 2 services and use on Controller on ASP.NET Core

I have a view Model:
public class CountViewModel
{
public int NewsLetterEmailCount { get; set; }
public int CurrentMonthNewsLetter { get; set; }
public int NewsLetterPercentage { get; set; }
}
then I create the second ViewModel that want to list of title:
public class AdminDashboardUnreadMessage
{
[Display(Name = "عنوان")]
public string Title { get; set; }
//public List<AdminDashboardUnreadMessage>
AdminDashboardUnreadMessages { get; set; }
}
I have a ticket Table, these are my 2 services:
public async Task<CountViewModel> AdminContentCount()
{
CountViewModel adminContetnCount = new CountViewModel()
{
UserCount = await _userRepository.UserCount(),
CurrentMonthUser = await _userRepository.CurrentMonthUser(),
NewsLetterEmailCount = await _newsLetterRepository.NewsLetterEmailCount(),
CurrentMonthNewsLetter = await _newsLetterRepository.CurrentMonthNewsLetterEmail(),
return adminContetnCount;
}
public async Task<List<AdminDashboardUnreadMessage>> ShowUnReadTicketMessages()
{
return await _userRepository.ShowUnReadTicketMessages();
}
How can I use 2 services on my service
I mean I don't want to use from View Data
I think you need to define a new ViewModel like this :
public class NewViewModel
{
public CountViewModel CountModel { get; set; }
public AdminDashboardUnreadMessage AdminDashboardModel { get; set; }
}
And now you need to return this object as a result of a newly created service which responsible to aggregate the result of two different services.
public async Task<NewViewModel> NewService()
{
var adminContetnCount = await AdminContentCount();
var dashboard = await ShowUnReadTicketMessages();
return new NewViewModel
{
CountModel = adminContetnCount,
AdminDashboardModel= dashboard
};
}

Why I couldn't call Model inside my Controller

I have one problem and I have no idea what to do. I am try couple of method but nothing works for me. I have model Patient
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace BergClinic.Models
{
public class Patient
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name ="First Name")]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[MaxLength(50)]
public string LastName { get; set; }
[Required]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Address")]
[MaxLength(50)]
public string Address { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Display(Name = "Gender")]
public PatientGender Gender { get; set; }
}
public enum PatientGender
{
[Display(Name ="Male")]
Male,
[Display(Name = "Female")]
Female,
Unknown
}
}
And IPatientRepository and PatientRepository which contains following logic:
using BergClinic.DataAccess.Data;
using BergClinic.DataAccess.Repository.IRepository;
using BergClinic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BergClinic.DataAccess.Repository
{
public class PatientRepository : Repository<Patient>, IPatientRepository
{
private readonly ApplicationDbContext _db;
public PatientRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public void Update(Patient patient)
{
var objDb = _db.Patients.FirstOrDefault(s => s.Id == patient.Id);
if (objDb != null)
{
objDb.FirstName = patient.FirstName;
objDb.LastName = patient.LastName;
objDb.DateOfBirth = patient.DateOfBirth;
objDb.Address = patient.Address;
objDb.PhoneNumber = patient.PhoneNumber;
objDb.Gender = patient.Gender;
_db.SaveChanges();
}
}
}
}
And here is IPatientRepository which containt Update method
using BergClinic.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BergClinic.DataAccess.Repository.IRepository
{
public interface IPatientRepository : IRepository<Patient>
{
void Update(Patient patient);
}
}
Once I creat this in my Admin Area in PatientController I want to initialize object Patient but I couldn't. I want to create Upsert method for Update and Insert Patient but whatever I type It doesn't see my model only what it is see is Patient workspace
'Patient' is a namespace but is used like a type
using BergClinic.DataAccess.Repository.IRepository;
using Microsoft.AspNetCore.Mvc;
using BergClinic.Models;
namespace BergClinic.Areas.Admin.Controllers
{
[Area("Admin")]
public class PatientController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public PatientController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IActionResult Index()
{
return View();
}
public IActionResult Upsert(int? Id)
{
Patient patient = new Areas.Patient
return View();
}
#region API_CALLS
[HttpGet]
public IActionResult GetAll()
{
var patient = _unitOfWork.Patient.GetAll();
return Json(new { data = patient });
}
#endregion
}
}
Just to notice I use RepositoryPatten and thee way arhitecture. I try to restart Visual Studio but seem nothing happened, I try to remove Project Reference and try to add again, but noting happened againg.
Here is couple of sceen of my ProjectStructures which you can check:

React axios post request to wcf web service

I am trying to post data from a react application to a wcf service class. Its a simple object with just name age and gender. The service is being called from the react app but with no data. If I use get request and parameter passing the data is passing to the service but I want to use post request. Is it necessary to match the field names as in the wcf service class.
For testing purpose in react component I am using this code
const headers = {
'content-type': 'application/json'
}
const puser = {
Name:'Test',
Age:'23',
Gender:'F',
}
axios.post('http://localhost:3292/myService.svc/adduser',{headers:headers}, puser)
.then(res=> {
console.log(res.data)
})
in wcf service the class code is
public class UserClass
{
string name;
int age;
string gender;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
}
and in service call
public string AddUser(List<User> U)
{
UserClass usr = new UserClass();
return "success";
}
Axios post method expects data as second argument. Try to swap puser with {headers}.
https://github.com/axios/axios#axiosposturl-data-config
Do not add header in axios.post, code should look like this:
const puser = {
Name:'Test',
Age:'23',
Gender:'F',
}
axios.post('http://localhost:8000/AddUser', puser)
.then(res=> {
console.log(res.data)
})
Feel free to let me know if the problem persists.
UPDATE:
Set header in Postman:
Axios.post can also set the header like the following:
axios.post('http://localhost:8000/AddUser',{ Name:'Test',
Age:'2311',
Gender:'FF'}, {headers: {
'content-type': 'application/json'
}})
.then(res=> {
console.log(res.data)
})
Here is my project:
Program.cs:
using Demo_rest_ConsoleApp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp71
{
public class User
{
string name;
int age;
string gender;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
}
[ServiceContract]
[CustContractBehavior]
public interface IService
{
[OperationContract]
[WebGet]
string EchoWithGet(string s);
[OperationContract]
[WebInvoke]
string EchoWithPost(string s);
[OperationContract]
[WebInvoke(ResponseFormat =WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json)]
string AddUser(User U);
}
public class Service : IService
{
public string AddUser(User U)
{
Console.WriteLine(U.Age);
Console.WriteLine(U.Gender);
Console.WriteLine(U.Name);
return "success";
}
public string EchoWithGet(string s)
{
return "You said " + s;
}
public string EchoWithPost(string s)
{
return "You said " + s;
}
}
class Program
{
static void Main(string[] args)
{
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
ep.EndpointBehaviors.Add(new WebHttpBehavior() { HelpEnabled=true});
host.Open();
Console.WriteLine("Open");
Console.ReadLine();
}
}
}
Soap.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
namespace Demo_rest_ConsoleApp
{
public class ServerMessageLogger : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
Console.WriteLine(request);
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
if (ctx.IncomingRequest.Method == "OPTIONS")
{
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,POST,DELETE,OPTIONS");
ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
}
}
}
public class ClientMessageLogger : IClientMessageInspector
{
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
}
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false)]
public class CustContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
{
public Type TargetContract => throw new NotImplementedException();
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
dispatchRuntime.MessageInspectors.Add(new ServerMessageLogger());
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
return;
}
}
}

Connection Between Kendo and SQL Server in ASP.NET Core

I am trying to do CRUD operation using Kendo UI to show my data in a grid view.
I can read the data from my database with the following code in my controller (my tables are in SQL Server and connected through a connection string):
[Area("Admin")]
public class HeaderMenuController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public HeaderMenuController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IActionResult Index()
{
return View();
}
public DataSourceResult Products_Read([DataSourceRequest] DataSourceRequest request)
{
return _unitOfWork.HeaderMenu.GetAll().ToDataSourceResult(request);
}
}
index.cshtml
#(Html.Kendo().Grid<MSDACE.Models.HeaderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.HeaderMenuID).Width(100);
columns.Bound(product => product.HeaderMenuName);
columns.Bound(product => product.HeaderMenuDispOrder).Width(250);
columns.Command(commands =>
{
commands.Destroy(); // The "destroy" command removes data items.
}).Title("Commands").Width(200);
})
.ToolBar(toolbar =>
{
toolbar.Create(); // The "create" command adds new data items.
toolbar.Save(); // The "save" command saves the changed data items.
})
.Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell editing mode.
.DataSource(dataSource =>
dataSource.Ajax()
.Batch(true) // Enable batch updates.
.Model(model =>
{
model.Id(product => product.HeaderMenuID); // Specify the property which is the unique identifier of the model.
model.Field(product => product.HeaderMenuID).Editable(false); // Make the ProductID property not editable.
})
.Create(create => create.Action("Products_Create", "HeaderMenu")) // Action method invoked when the user saves a new data item.
.Read(read => read.Action("Products_Read", "HeaderMenu")) // Action method invoked when the Grid needs data.
.Update(update => update.Action("Products_Update", "HeaderMenu")) // Action method invoked when the user saves an updated data item.
.Destroy(destroy => destroy.Action("Products_Destroy", "HeaderMenu")) // Action method invoked when the user removes a data item.
)
.Pageable()
)
The problem is I can't the delete or create operations.
I have written the GetAll, Remove, Get and other functions, but my problem is to reflect in the Kendo Grid
IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
IHeaderMenuRepository HeaderMenu { get; }
void Save();
}
IHeaderMenuRepository.cs
public class HeaderMenuRepository : Repository<HeaderMenu>, IHeaderMenuRepository
{
private readonly ApplicationDbContext _db;
public HeaderMenuRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public IEnumerable<SelectListItem> GetHeaderMenuList()
{
return _db.HeaderMenu.Select(i => new SelectListItem()
{
Text = i.HeaderMenuName,
Value = i.HeaderMenuID.ToString()
});
}
public void Update(HeaderMenu headerMenu)
{
var objFrobDb = _db.HeaderMenu.FirstOrDefault(s => s.HeaderMenuID == headerMenu.HeaderMenuID);
objFrobDb.HeaderMenuName = headerMenu.HeaderMenuName;
objFrobDb.HeaderMenuDesc = headerMenu.HeaderMenuDesc;
objFrobDb.HeaderMenuActive = headerMenu.HeaderMenuActive;
objFrobDb.HeaderMenuDispOrder = headerMenu.HeaderMenuDispOrder;
_db.SaveChanges();
}
IRepository
public interface IRepository<T> where T : class
{
T Get(int id);
IEnumerable<T> GetAll(
Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = null
);
T GetFirstOrDefault(
Expression<Func<T, bool>> filter = null,
string includeProperties = null
);
void Add(T entity);
void Remove(int id);
void Remove(T entity);
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _db;
public UnitOfWork(ApplicationDbContext db)
{
_db = db;
HeaderMenu = new HeaderMenuRepository(_db);
}
public IHeaderMenuRepository HeaderMenu { get; private set; }
public void Dispose()
{
_db.Dispose();
}
public void Save()
{
_db.SaveChanges();
}
}
Repository.cs
public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext Context;
internal DbSet<T> dbSet;
public Repository(DbContext context)
{
Context = context;
this.dbSet = context.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public T Get(int id)
{
return dbSet.Find(id);
}
public IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
public T GetFirstOrDefault(Expression<Func<T, bool>> filter = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
return query.FirstOrDefault();
}
public void Remove(int id)
{
T entityToRemove = dbSet.Find(id);
Remove(entityToRemove);
}
public void Remove(T entity)
{
dbSet.Remove(entity);
}
}
HeaderMenuRepository.cs
public class HeaderMenuRepository : Repository<HeaderMenu>, IHeaderMenuRepository
{
private readonly ApplicationDbContext _db;
public HeaderMenuRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public IEnumerable<SelectListItem> GetHeaderMenuList()
{
return _db.HeaderMenu.Select(i => new SelectListItem()
{
Text = i.HeaderMenuName,
Value = i.HeaderMenuID.ToString()
});
}
public void Update(HeaderMenu headerMenu)
{
var objFrobDb = _db.HeaderMenu.FirstOrDefault(s => s.HeaderMenuID == headerMenu.HeaderMenuID);
objFrobDb.HeaderMenuName = headerMenu.HeaderMenuName;
objFrobDb.HeaderMenuDesc = headerMenu.HeaderMenuDesc;
objFrobDb.HeaderMenuActive = headerMenu.HeaderMenuActive;
objFrobDb.HeaderMenuDispOrder = headerMenu.HeaderMenuDispOrder;
_db.SaveChanges();
}
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<HeaderMenu> HeaderMenu { get; set; }
}
The problem is I cant to the Delete, Create or Edit operation!
I Belive that I can not make the connection between the Kendo and my Database and have to implement something in my controller.
I try the Kendo.MVC examples but the problem are the northwind and sqllite the used!
Could please help me by this issue to implement the CRUD on Grid using the data in my sqlserver tables.

asp.net core web api returns 500 server error

I am new to asp.net Web API. I am using EF Core to work with data. I have two tables in SQL Server, USER_DATA and WORK_DATA.
I am trying to send HTTP GET request and fetch data from WORK_DATA table, but the response is a 500 error and says no content. I can Get and Post completely to USER_DATA. I could not only fetch WORK_DATA. I think that routing is correct and the struct of SQL Server's table s wrong but I do not know how to fix it.
SQL Server struct is here: the database has two tables USER_DATA and WORK_DATA:
USER_DATA has these columns
Id (PK, varchar, notnull)
UserName (varchar, null)
RegisterDate (Date, null)
Field (varchar, null)
Password (varchar, null)
Heats (int, null)
WORK_DATA has these columns
WorkId (PK, varchar, notnull)
WorkName (varchar, null)
Detailinformation (varchar, null)
Salary (varchar, null)
Worklength (varchar, null)
Reliability (int, null)
RegisterDate (date, null)
isCompleted (bit, null)
Id (varchar, not null)
Foreign key is Id and it reference USER_DATA.Id.
Models are here - Item corresponds to USER_DATA in SQL Server, Workdata corresponds to WORK_DATA.
Item
using System;
using System.Collections.Generic;
namespace NewHeats.Models
{
public class Item
{
public string Id { get; set; }
public string UserName { get; set; }
public DateTime RegisterDate { get; set; }
public string Field { get; set; }
public string Password { get; set;}
public int Heats { get; set; }
}
}
Workdata:
using System;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace NewHeats.Models
{
public class Workdata
{
public string WorkId { get; set; }
public string WorkName { get; set; }
public string DetailInformation { get; set; }
public string Salary { get; set; }
public string Worklength { get; set; }
public int Reliability { get; set; }
public DateTime RegisterDate { get; set; }
public int isCompleted { get; set; }
public string Id { get; set; }
[ForeignKey("Id")]
public Item Item { get; set; }
}
}
DbContext:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
namespace NewHeats.Models
{
public class ItemRepository : DbContext ,IItemRepository
{
public ItemRepository(DbContextOptions<ItemRepository> options)
: base(options)
{
}
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
try
{
modelBuilder.Entity<Item>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("USER_DATA");
});
modelBuilder.Entity<Workdata>(entity =>
{
entity.HasKey(e => e.WorkId);
entity.ToTable("WORK_DATA");
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public virtual DbSet<Item> USER_DATA { get; set; }
public virtual DbSet<Workdata> WORK_DATA { get; set; }
public Item Get(string id)
{
return USER_DATA.FirstOrDefault(x => x.Id == id);
}
public IEnumerable<Item> GetAll()
{
return USER_DATA.ToList();
}
public void Add(Item item)
{
item.Id = Guid.NewGuid().ToString();
USER_DATA.Add(item);
}
public Item Find(string id)
{
return USER_DATA.FirstOrDefault(x=>x.Id==id);
}
public Item Remove(string id)
{
return USER_DATA.FirstOrDefault(x => x.Id == id);
}
public void Update(Item item)
{
USER_DATA.Remove(USER_DATA.FirstOrDefault(x => x.Id == item.Id));
USER_DATA.Add(item);
}
public Workdata GetWorkdata(string workId)
{
return WORK_DATA.FirstOrDefault(x => x.WorkId == workId);
}
public IEnumerable<Workdata> GetAllWorkdata()
{
return this.WORK_DATA.ToList();
}
public void AddWorkdata(Workdata workdata)
{
workdata.WorkId = Guid.NewGuid().ToString();
WORK_DATA.Add(workdata);
}
public Workdata FindWorkdata(string workId)
{
return WORK_DATA.FirstOrDefault(x => x.WorkId == workId);
}
public Workdata RemoveWorkdata(string workId)
{
return WORK_DATA.FirstOrDefault(x => x.WorkId == workId);
}
public void UpdateWorkdata(Workdata workdata)
{
WORK_DATA.Remove(WORK_DATA.FirstOrDefault(x => x.WorkId == workdata.WorkId));
WORK_DATA.Add(workdata);
}
}
}
IItemRepository:
using System;
using System.Collections.Generic;
using System.Linq;
namespace NewHeats.Models
{
public interface IItemRepository
{
void Add(Item item);
void Update(Item item);
Item Remove(string key);
Item Get(string id);
IEnumerable<Item> GetAll();
void AddWorkdata(Workdata workdata);
void UpdateWorkdata(Workdata workdata);
Workdata RemoveWorkdata(string workid);
Workdata GetWorkdata(string workid);
IEnumerable<Workdata> GetAllWorkdata();
}
}
Controllers are here
ItemController
Corresponds to my USER_DATA table in SQL Server
using System;
using Microsoft.AspNetCore.Mvc;
using NewHeats.Models;
namespace NewHeats.Controllers
{
[Route("api/[controller]")]
public class ItemController : Controller
{
private ItemRepository _itemRepository;
public ItemController(ItemRepository itemRepository)
{
_itemRepository = itemRepository;
}
[HttpGet]
public IActionResult List()
{
return Ok(_itemRepository.GetAll());
}
[HttpGet("{Id}")]
public Item GetItem(string id)
{
Item item = _itemRepository.Get(id);
return item;
}
[HttpPost]
public IActionResult Create([FromBody]Item item)
{
try
{
if (item == null || !ModelState.IsValid)
{
return BadRequest("Invalid State");
}
_itemRepository.Add(item);
_itemRepository.SaveChanges();
}
catch (Exception)
{
return BadRequest("Error while creating");
}
return Ok(item);
}
[HttpPut]
public IActionResult Edit([FromBody] Item item)
{
try
{
if (item == null || !ModelState.IsValid)
{
return BadRequest("Invalid State");
}
_itemRepository.Update(item);
_itemRepository.SaveChanges();
}
catch (Exception)
{
return BadRequest("Error while creating");
}
return NoContent();
}
[HttpDelete("{Id}")]
public void Delete(string id)
{
_itemRepository.Remove(id);
_itemRepository.SaveChanges();
}
}
}
WorkdataController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NewHeats.Models;
namespace NewHeats.MobileAppService.Controllers
{
[Route("api/[controller]")]
public class WorkdataController :Controller
{
private ItemRepository _itemRepository;
public WorkdataController(ItemRepository itemRepository)
{
_itemRepository = itemRepository;
}
[HttpGet]
public IActionResult List()
{
return Ok(_itemRepository.GetAllWorkdata());
}
[HttpGet("{WorkId}")]
public Workdata GetItem(string workId)
{
Workdata workdata = _itemRepository.GetWorkdata(workId);
return workdata;
}
[HttpPost]
public IActionResult Create([FromBody]Workdata workdata)
{
try
{
if (workdata == null || !ModelState.IsValid)
{
return BadRequest("Invalid State");
}
_itemRepository.AddWorkdata(workdata);
_itemRepository.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return BadRequest("Error while creating");
}
return Ok(workdata);
}
[HttpPut]
public IActionResult Edit([FromBody] Workdata workdata)
{
try
{
if (workdata == null || !ModelState.IsValid)
{
return BadRequest("Invalid State");
}
_itemRepository.UpdateWorkdata(workdata);
_itemRepository.SaveChanges();
}
catch (Exception)
{
return BadRequest("Error while creating");
}
return NoContent();
}
[HttpDelete("{WorkId}")]
public void Delete(string workId)
{
_itemRepository.RemoveWorkdata(workId);
_itemRepository.SaveChanges();
}
}
}
I am trying to solve this problem a week but I could not. I searched a lot of stackoverflow , msdn etc... Please help me.
Thanks

Resources