I'm currently builiding an ASP .NET MVC application but I'm getting this error in my program. Not really sure what I did wrong.
This is my model: ProfileCreationContext
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using System.IO;
using Microsoft.Data.SqlClient;
using System.Data;
namespace CRUD_Profile_Creation.Models
{
public class ProfileCreationContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:UserProfile"]);
}
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HDBEK6R;Initial Catalog=Bottleneckv1;Integrated Security=True");
public DbSet<ProcessUnit> ProcessUnit { get; set; }
}
}
This is my other model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Profile_Creation.Models
{
public class ProcessUnit
{
public string ProcessUnitID { get; set; }
public string ProcessUnitName { get; set;}
public int ProcessTypeID { get; set;}
public string InventoryName { get; set;}
public string CumM { get; set;}
public string PerdayM { get; set;}
public string TotalM { get; set; }
}
}
And this is my controller:
using CRUD_Profile_Creation.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Profile_Creation.Controllers
{
public class ProcessUnitController : Controller
{
private ProfileCreationContext db = new ProfileCreationContext();
public IActionResult Index()
{
ViewBag.processUnitID = db.ProcessUnitID.ToList();
ViewBag.processUnitID = db.ProcessUnitName.ToList();
ViewBag.processUnitID = db.ProcessTypeID.ToList();
ViewBag.processUnitID = db.InventoryName.ToList();
ViewBag.processUnitID = db.CumM.ToList();
ViewBag.processUnitID = db.PerdayM.ToList();
ViewBag.processUnitID = db.TotalM.ToList();
return View();
}
}
}
This is the error I'm getting.
I'm still new in this framework. Im doing this based off my past personal projects
THE SOLUTION I DID
so basically, what I wanted was to list out all the items in the table. this is how I fixed it. I needed just to call that. Not sure why I started by listing all the variables. Hope this helps!
My controller:
public class DenoProfileController : Controller
{
private ProfileCreationContext db = new ProfileCreationContext();
public IActionResult Index()
{
ViewBag.denoprofile = db.DenoProfile.ToList();
return View();
}
}
first sorry if my english isn't good enough XD. Second, I'm programing on ASP.NET Core 2.0. And when i launch my webapp i get the next error when i try to go to the "Clases" web page of my App.
InvalidOperationException: Unable to resolve service for type 'EduCloud.Data.IClassInfo' while attempting to activate 'EduCloud.Controllers.UnitsController'.
Before all, sorry if it is too much code. The code for the Model involve is
using System;
using System.Collections.Generic;
using System.Text;
namespace EduCloud.Data.Models
{
public class ClassInfo
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ClassVideoUrl { get; set; }
public string ClassHomeworkUrl { get; set; }
public string TestUrl { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Forum Forum { get; set; }
}
}
This Model has 1 level of abstraction with the class
using EduCloud.Data.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace EduCloud.Data
{
public interface IClassInfo
{
ClassInfo GetById(int id);
IEnumerable<ClassInfo> GetAll();
IEnumerable<ClassInfo> GetFilteredClasses(Forum forum, string searchQuery);
IEnumerable<ClassInfo> GetFilteredClasses(string searchQuery);
IEnumerable<ClassInfo> GetClassesByForum(int id);
Task Add(ClassInfo classInfo);
Task Delete(int id);
Task EditClassContent(int id, string newContent);
}
}
Next, the methods of the this IClass are in the next class
using EduCloud.Data;
using EduCloud.Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EduCloud.Service
{
public class ApplicationClassService : IUnit
{
private readonly ApplicationDbContext _context;
public ApplicationClassService(ApplicationDbContext context)
{
_context = context;
}
public async Task Create(ClassInfo classInfo)
{
_context.Add(classInfo);
await _context.SaveChangesAsync();
}
public Task Delete(int classId)
{
throw new NotImplementedException();
}
public IEnumerable<Forum> GetAll()
{
return _context.Forums
.Include(forum => forum.Classes);
}
public Forum GetById(int id)
{
var forum = _context.Forums.Where(f => f.Id == id)
.Include(f => f.Classes ).ThenInclude(p => p.User)
//.Include(f => f.Classes).ThenInclude(p => p.Replies).ThenInclude(r => r.User)
.FirstOrDefault();
return forum;
}
public Task UpdateForumTitle(int classId, string newTitle)
{
throw new NotImplementedException();
}
}
}
Finally the Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EduCloud.Data;
using EduCloud.Data.Models;
using EduCloud.Models.Classes;
using EduCloud.Models.Units;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace EduCloud.Controllers
{
public class UnitsController : Controller
{
private readonly IUnit _unitService;
private readonly IForum _forumService;
private readonly IClassInfo _classService;
public UnitsController(IUnit unitService, IForum forumService, IClassInfo classService)
{
_unitService = unitService;
_forumService = forumService;
_classService = classService;
}
public IActionResult Index()
{
var units = _unitService.GetAll()
.Select(forum => new UnitsListingModel
{
Id = forum.Id,
Name = forum.Title,
});
var model = new UnitsIndexModel
{
UnitList = units
};
return View(model);
}
}
}
And the code of the view that i try to run when i go to the "Clases" link
#model EduCloud.Models.Units.UnitsIndexModel
<h1>Unidades de Aprendizaje</h1>
<table class="table table-hover" id="forumIndexTable">
<tbody>
#foreach (var forum in Model.UnitList)
{
<tr>
<td>
<a asp-controller="Units" asp-action="ClassesList" asp-route-id="#forum.Id">
#forum.Name
</a>
</td>
</tr>
}
</tbody>
</table>
I started develop my project - web application with Database. I used WEB API with entity framework
I need CRUD operations realize in my project.
Read - work fine
But I don't know how realize Create, Update, Delete; I don't have enough experience and be glad yours advice.
I tried realize good architecture of my application - using repository pattern and fabric pattern. If you have advice in architecture of my project , I'll be grateful you.
I don't know how realize it in value controller and repository, could you help please?
Attach my code:
Repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebAPI
{
public class CustomerRepository
{
public IQueryable<Customer> GetAllCustomers()
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers;
}
public IQueryable<Customer> GetAllCustomers(int id)
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers.Where(c=>c.Id==id).Select(e=>e);
}
public IQueryable<Customer> DeleteCustomer(int id)
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers.Remove(id);
}
public IQueryable<Customer> CreateCustomer()
{
DevelopersEntities dev = new DevelopersEntities();
}
public IQueryable<Customer> UpdateCustomer(int id)
{
DevelopersEntities dev = new DevelopersEntities();
}
}
}
Customer model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAPI;
namespace DevelopersWeb.Models
{
public class CustomerModel
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public IEnumerable<HardwareModel> Hardware { get; set; }
public IEnumerable<SoftwareModel> Software { get; set; }
}
}
Harware Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevelopersWeb.Models
{
public class HardwareModel
{
public int HardwareId { get; set; }
public string HardwareName { get; set; }
}
}
Software Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevelopersWeb.Models
{
public class SoftwareModel
{
public int SoftwareId { get; set; }
public string SoftwareName { get; set; }
}
}
Model Factory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAPI;
namespace DevelopersWeb.Models
{
public class ModelFactory
{
public CustomerModel Create(Customer customer)
{
return new CustomerModel()
{
CustomerId = customer.Id,
CustomerName = customer.Name,
Hardware = customer.HardWares.Select(h=>Create(h)),
Software = customer.Softwares.Select(c=>Create(c))
};
}
public HardwareModel Create(HardWare hardware)
{
return new HardwareModel()
{
HardwareId = hardware.HardWareId,
HardwareName = hardware.HardWareName,
};
}
public SoftwareModel Create(Software software)
{
return new SoftwareModel()
{
SoftwareId = software.SoftwareId,
SoftwareName = software.SoftwareName
};
}
}
}
Value Controller
using DevelopersWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI;
namespace DevelopersWeb.Controllers
{
public class ValuesController : ApiController
{
ModelFactory _modelFactory;
public ValuesController()
{
_modelFactory = new ModelFactory();
}
// GET api/values
public IEnumerable<CustomerModel> Get()
{
CustomerRepository cr = new CustomerRepository();
return cr.GetAllCustomers().ToList().Select(c=> _modelFactory.Create(c));
}
// GET api/values/5
public string Get(int id)
{
return "xxx";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Here is how you should save customer object:
public void CreateCustomer(Customer customer)
{
DevelopersEntities dev = new DevelopersEntities();
dev.Customers.Add(customer)
dev.SaveChanges();
}
Here is you api action:
// POST api/values
public void Post([FromBody]CustomerModel customerModel)
{
//Here you should transform CustomerModel object to customerEntity
CustomerRepository cr = new CustomerRepository();
cr.CreateCusomer(customer);
return Ok();
}
You should think about using Dependency Injection pattern here as well.
I want to create a route attribute in the Porosi controller, in the detaje method that takes as a DatePorosie (DatePorosie is the date) on parameter. The method must display from Porosi.cs class EmriPorosise, DatePorosie, TotaliPorosise according to the date that comes as a parameter in url. (sending date value either by form or by link). I hope I explained it well. Can you help me please???
This is Porosi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcProjektDb.Models
{
public class Porosi
{
public int PorosiId { get; set; }
public string EmriPorosise { get; set; }
public DateTime DatePorosie { get; set; }
public int TotaliPorosise { get; set; }
public int? KlienteId { get; set; }
public virtual Kliente Kliente { get; set; }
}
}
This is PorosiController.cs but I don't know what to do here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcProjektDb.Migrations;
using MvcProjektDb.Models;
namespace MvcProjektDb.Controllers
{
public class PorosiController : Controller
{
private ApplicationDbContext _db;
public PorosiController()
{
_db = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
}
// GET: Porosi
public ActionResult Index()
{
return View();
}
[Route("Porosi/detaje/{dateporosie?}")]
public ActionResult detaje(DateTime? dateporosie)
{
var x = _db.porosi.Where(p => p.DatePorosie == dateporosie).ToList();
return View(x);
}
}
}
Im learning ASP.NET CORE , and also Im building my first web project.
The project is about renting cars. I will show what've done so far to the project and what is my problem.
I implement the data models:
1
2.I write the CarCategory properties and so on.
namespace CarRentalSystem.Data.Models
{
using System.Collections.Generic;
using CarRentalSystem.Data.Common.Models;
public class CarCategory : BaseDeletableModel<int>
{
public CarCategory()
{
this.SmallCars = new HashSet<SmallCarInfo>();
}
public string Name { get; set; }
public string Title { get; set; }
public string CarDescription { get; set; }
public string CarImageUrl { get; set; }
public virtual ICollection<SmallCarInfo> SmallCars { get; set; }
}
}
3.My home controller:
namespace CarRentalSystem.Web.Controllers
{
using System.Diagnostics;
using System.Linq;
using CarRentalSystem.Data;
using CarRentalSystem.Services.Data;
using CarRentalSystem.Web.ViewModels;
using CarRentalSystem.Web.ViewModels.Administration.Dashboard;
using CarRentalSystem.Web.ViewModels.Home;
using Microsoft.AspNetCore.Mvc;
public class HomeController : BaseController
{
private readonly ICategoriesService categoriesService;
public HomeController(ICategoriesService categoriesService)
{
this.categoriesService = categoriesService;
}
public IActionResult Index()
{
var viewModel = new IndexViewModels
{
Categories = this.categoriesService.GetAll<IndexCategoryViewModel>(),
};
// var categories = this.db.CarCategories.Select(x => new IndexCategoryViewModel
// {
// Title = x.Title,
// CarDescription = x.CarDescription,
// Name = x.Name,
// CarImageUrl = x.CarImageUrl,
// }).ToList();
// viewModel.Categories = categories;
return this.View(viewModel);
}
public IActionResult Privacy()
{
return this.View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return this.View(
new ErrorViewModel { RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier });
}
}
}
4.I write some code on it.I make services and ViewModels
namespace CarRentalSystem.Web.ViewModels.Home
{
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class IndexCategoryViewModel : IMapFrom<CarCategory>
{
public string Title { get; set; }
public string CarDescription { get; set; }
public string Name { get; set; }
public string CarImageUrl { get; set; }
public string Url => $"/c/{this.Name.Replace(' ', '-')}";
}
}
namespace CarRentalSystem.Web.ViewModels.Home
{
using System;
using System.Collections.Generic;
using System.Text;
public class IndexViewModels
{
public IEnumerable<IndexCategoryViewModel> Categories { get; set; }
}
}
namespace CarRentalSystem.Services.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarRentalSystem.Data.Common.Repositories;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CategoriesService : ICategoriesService
{
private readonly IDeletableEntityRepository<CarCategory> categoriesRepository;
public CategoriesService(IDeletableEntityRepository<CarCategory> categoriesRepository)
{
this.categoriesRepository = categoriesRepository;
}
public IEnumerable<T> GetAll<T>(int? count = null)
{
IQueryable<CarCategory> query =
this.categoriesRepository.All();
if (count.HasValue)
{
query = query.Take(count.Value);
}
return query.To<T>().ToList();
}
public T GetByName<T>(string name)
{
var category = this.categoriesRepository.All().Where(x => x.Name == name)
.To<T>().FirstOrDefault();
return category;
}
}
}
5.This is the service that I use, next I make VIEW, the whole database , also a seeder for the the thigs that I need and my home page is ready
namespace CarRentalSystem.Data.Seeding
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using Microsoft.EntityFrameworkCore.Internal;
public class CategoriesSeeder : ISeeder
{
public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
{
if (dbContext.CarCategories.Any())
{
return;
}
var carCategories = new List<(string Name, string ImageUrl, string CarDescription)>
{
("Small car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/city-car-128.png",
"This is a compact car with 2/3 doors. Perfect for couples with small luggage."),
("Medium car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/sedan-128.png",
"This is medium car with 4/5 doors. Perfect for small families with average luggage."),
("Minivan", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/minivan-128.png",
"This is a large car with 4/5 doors + extra seats. Perfect for large families with average luggage."),
("Minibus", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/van-128.png",
"This is a large car with 8+1 seats with big trunk. Perfect for large families or companies with a lot of luggage"),
};
foreach (var category in carCategories)
{
await dbContext.CarCategories.AddAsync(new CarCategory
{
Name = category.Name,
Title = category.Name,
CarImageUrl = category.ImageUrl,
CarDescription = category.CarDescription,
});
}
}
}
}
#using CarRentalSystem.Common
#model CarRentalSystem.Web.ViewModels.Home.IndexViewModels
#{
this.ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome to ElisCar</h1>
</div>
<div class="row">
#foreach (var category in Model.Categories)
{
<div class="col-md-2 card m-auto" style="width: 18rem;">
<img src="#category.CarImageUrl" width="100" class="card-img-top" alt="#category.Title">
<div class="card-body">
<h5 class="card-title">#category.Title</h5>
#category.CarDescription
Reservation
</div>
</div>
}
</div>
My home page
6.After this I want to choose cars from the categories and im getting this errors
3
7.I know why im getting NullReferenceException , because I dont have any data , the problem is that I cant seed them.
8.My secont controller for the RESERVATION button
namespace CarRentalSystem.Web.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Data;
using CarRentalSystem.Web.ViewModels.Categories;
using Microsoft.AspNetCore.Mvc;
public class CategoriesController : Controller
{
private readonly ICategoriesService categoriesService;
public CategoriesController(ICategoriesService categoriesService)
{
this.categoriesService = categoriesService;
}
public IActionResult ChooseCars(string name)
{
var viewModel =
this.categoriesService.GetByName<CarsViewModel>(name);
if (viewModel == null)
{
return this.NotFound();
}
return this.View(viewModel);
}
}
}
9.The ViewModels
namespace CarRentalSystem.Web.ViewModels.Categories
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CarsViewModel : IMapFrom<CarCategory>
{
public string Title { get; set; }
public string Name { get; set; }
public string CarDescription { get; set; }
public string CarImageUrl { get; set; }
public IEnumerable<CarsListViewModel> CarDetails { get; set; }
}
}
namespace CarRentalSystem.Web.ViewModels.Categories
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CarsListViewModel : IMapFrom<SmallCarInfo>
{
public string CarModel { get; set; }
public string CarImage { get; set; }
public int CarPricePerDay { get; set; }
}
}
The SmallCarsInfo Base model
4
Now Im trying to seed another data to the databse , to add car make , price etc:
5
12.The VIEW of the second controller:
#using CarRentalSystem.Common
#model CarRentalSystem.Web.ViewModels.Categories.CarsViewModel
#{
this.ViewData["Title"] = "Cars";
}
<h1 class="display-3">Hello!</h1>
<div class="row">
#foreach (var details in Model.CarDetails)
{
<div class="card" style="width: 18rem;">
<img src="#details.CarImage" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#details.CarModel</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">#details.CarPricePerDay euro.</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
<div class="card-body">
Card link
Another link
</div>
</div>
}
</div>
13.Now I put the seeders to the StartUp to implement them:
var seeders = new List<ISeeder>
{
new RolesSeeder(),
new SettingsSeeder(),
new CategoriesSeeder(),
new SmallCarsSeeder(),
};
14.And now when I start the project I get this error:
7
15.Also im not getting any data to the database in SmallCar:
8
The first seeder is working and everything is fine in the Home Page , but when I click the RESERVATION button , I got NullReferenceException, then I put the second seeder to take more data and its not working , I have no idea what is going on.
It looks to me like inside your SeedAsync method, after the foreach loop adding the items to the DB Context, you need to call dbContext.SaveChanges(); which will 'commit' the added items to the actual database. Otherwise you are just adding them to the in-memory tracking. Try this and see if it helps.