I am currently making a small application with basic CRUD operations and I want to display all Books in my View. But when I call .Booksobject it's written that:
'IndexModel' does not contain a definition for 'Books' and no accessible extension method 'Books' accepting a first argument of type 'IndexModel' could be found (are you missing a using directive or an assembly reference?)
Here is what I did so far:
Book Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Razor_2_1.Model
{
public class Book
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string ISBN { get; set; }
public string Author { get; set; }
}
}
ApplicationDbContext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Razor_2_1.Model
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Book> Books { get; set; }
}
}
Index.html.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CRUD_Razor_2_1.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace CRUD_Razor_2_1.Pages.BookList
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
public CreateModel(ApplicationDbContext db)
{
_db = db;
}
[BindProperty]
public Book Book { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPost()
{
if(!ModelState.IsValid)
{
return Page();
}
_db.Books.Add(Book);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}
And here when I want to call Model.Book.Count() is where I get the error:
#page
#model IndexModel;
#{
}
<br />
<h2>Book List</h2>
<br />
<a asp-page="Create" class="btn btn-primary">Create New Book</a>
#if(Model.Books.Count() > 0)
{
}
else
{
}
Related
I'm trying to make a webpage in c# .net core razorpages. Basically I want the values of a specific column from my postgresql table in a list, and then show these values in the select option in html. But I'm having some problems on the c# side. I get this error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List<Project_Corona.Models.WorkspaceModel>' [Project_Corona]
Here is the code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Controllers
{
public class HomeController : Controller
{
public IActionResult Employeepage()
{
var cs = Database.Database.Connector();
using var con = new NpgsqlConnection(cs);
con.Open();
List<WorkspaceModel> res = new List<WorkspaceModel>();
res = ("Select location FROM workspaces").ToList();
return View();
}
}
}
This is the code from WorkspaceModel.cs (if necessary)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Models
{
public class WorkspaceModel
{
[BindProperty]
public string LocationName { get; set; }
[BindProperty]
public string RoomName { get; set; }
[BindProperty]
public int SquareMeters { get; set; } = 1;
[BindProperty]
public int Lengthws { get; set; } = 1;
[BindProperty]
public int Widthws { get; set; } = 1;
}
}
Have you tried to use EntityFramework Core for PostgreSQL to query your database?
I created a small example here
Simply create a DbContext with your database server settings:
public class WorkspaceContext : DbContext
{
public DbSet<WorkspaceModel> Workspaces { get; set; }
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase("inmemory");
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_pw");
}
... and call container.AddDbContext<WorkspaceContext>(); in your Dependency Injection configuration.
Now you can query your underlying database very easy by calling:
var res = ctx.Workspaces.Select(w => w.LocationName);
// var res = ctx.Workspaces.FromSqlRaw("Select location FROM workspaces");
Then you will get the result according to your sql statement: Select location FROM workspaces
I have problem with my first web application , when I start the application Im getting this error:
1st img
2nd img
The application is about car rental.
1.I will show my data structure: for CarCategory and SmallCars
--CARCATEGORY
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; }
}
}
--SMALLCARS
namespace CarRentalSystem.Data.Models
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Common.Models;
public class SmallCarInfo : BaseModel<int>
{
public string CarModel { get; set; }
public string CarImage { get; set; }
public int CarPricePerDay { get; set; }
public int CategoryId { get; set; }
public virtual CarCategory Category { get; set; }
}
}
Now I make a migration and im going to make two SEEDERS with data:
--CAR CATEGORIES SEEDER
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,
});
}
dbContext.SaveChanges();
}
}
}
--SMALL CARS SEEDER
namespace CarRentalSystem.Data.Seeding
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using Microsoft.EntityFrameworkCore.Internal;
public class SmallCarsSeeder : ISeeder
{
public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
{
if (dbContext.SmallCar.Any())
{
return;
}
var carDetails = new List<(string CarModel, string CarImage, int CarPricePerDay)>
{
("Nissan Micra", "https://5.imimg.com/data5/BV/XC/RV/SELLER-85643879/nissan-micra-xl-o-cvt-turquoise-blue-1198-cm3-car-500x500.jpg", 15),
("Ford Fiesta", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT_s9VktREdvkJUF9uU2V4NWIOzxU4Olk8IdTO2DOfjbAnsJQcU&usqp=CAU", 15),
};
foreach (var details in carDetails)
{
await dbContext.SmallCar.AddAsync(new SmallCarInfo
{
CarModel = details.CarModel,
CarImage = details.CarImage,
CarPricePerDay = details.CarPricePerDay,
});
}
dbContext.SaveChanges();
}
}
}
3.Now Im making CONTROLLERS + SERVICES/VIEW-MODELS and VIEWS
--CONTROLLER FOR CHOOSING SMALL CARS
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<CarsListViewModel>(name);
return this.View(viewModel);
}
}
}
--"GetByName" SERVICE LOGIC
namespace CarRentalSystem.Services.Data
{
using System;
using System.Collections.Generic;
using System.Text;
public interface ICategoriesService
{
IEnumerable<T> GetAll<T>(int? count = null);
T GetByName<T>(string name);
}
}
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.Replace(" ", "-") == name.Replace(" ", "-"))
.To<T>().FirstOrDefault();
return category;
}
}
}
-- TWO VIEW-MODELS THAT GET DATA FROM DATA MODELS AND MAPPING
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<CarCategory>
{
public string Name { get; set; }
public string Title { get; set; }
public string CarDescription { get; set; }
public IEnumerable<CarsViewModel> SmallCars { 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 CarsViewModel : IMapFrom<SmallCarInfo>
{
public string CarModel { get; set; }
public string CarImage { get; set; }
public int CarPricePerDay { get; set; }
}
}
--THE VIEW WITH RAZOR
#using CarRentalSystem.Common
#model CarRentalSystem.Web.ViewModels.Categories.CarsListViewModel
#{
this.ViewData["Title"] = "Cars";
}
<h1 class="display-3">#Model.Title</h1>
<div class="row">
#foreach (var details in Model.SmallCars)
{
<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>
And now when I start the app Im getting the error that I showed at the top.
Picture of the CARCATEGORY table
Picture of the SMALLCARS table
How can I fix the problem with FK confliction? Thanks!
How to perform model unit testing in .net core 2.0? I am not getting what to pass to Homecontroller class in unit testing class. This is my unit testing class where I need help
using BasicUnitTesting.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BasicUnitTesting.Controllers;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace BasicUnitTestProj
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void GetEmployeeTest()
{
HomeController home = new HomeController(null); //What should i pass to HomeController
var vr = home.GetEmployee() as ViewResult;
List<Employee> expectedemps = new List<Employee>()
{
new Employee() {EmpID=101,EmpName="Abhilash",Salary=50000},
new Employee() {EmpID=102,EmpName="Abhishek",Salary=60000},
new Employee() {EmpID=103,EmpName="Nagraj",Salary=30000},
new Employee() {EmpID=104,EmpName="Sunil",Salary=50000},
new Employee() {EmpID=105,EmpName="Vinay",Salary=40000}
};
Assert.IsTrue(expectedemps.SequenceEqual(vr.Model as List<Employee>));
}
}
}
Below is my Homecontroller
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BasicUnitTesting.Models;
namespace BasicUnitTesting.Controllers
{
public class HomeController : Controller
{
private readonly CompanyDbContext _context
public HomeController(CompanyDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View("Index");
}
public IActionResult GetEmployee()
{
//CompanyDbContext Db = new CompanyDbContext();
//List<Employee> emps = Db.Employees.ToList();
List<Employee> emps = _context.Employees.ToList();
return View(emps);
}
}
}
My model and Context class are as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
namespace BasicUnitTesting.Models
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
public class CompanyDbContext:DbContext
{
public CompanyDbContext()
{
}
public CompanyDbContext(DbContextOptions<CompanyDbContext> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
You should pass abstraction/interface to your Controller, it should not know about details/implementation of your DbContext.
What you need is another Interface/Contract:
public interface ICompanyDbContext
{
DbSet<Employee> Employees { get; set; }
}
and your class should implement this interface:
public class CompanyDbContext: ICompanyDbContext, DbContext
Your controller should have argument of ICompanyDbContext not CompanyDbContext:
public HomeController(ICompanyDbContext context)
This allows you to mock ICompanyDbContext in your unit test:
var dbContext = new Mock<ICompanyDbContext>();
// you should SetUp mock as well as do verification on it
HomeController home = new HomeController(dbContext.Object);
Hi there im following the series of MVC tutorials given by microsoft and i came across this problem:
Error 1 The best overloaded method match for
'System.Data.Entity.DbSet.Add(Conference.Models.Session)'
has some invalid arguments visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 18 31 Conference
Error 2 Argument 1: cannot convert from 'Conference.Models.Speaker' to
'Conference.Models.Session' visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 19 34 Conference
ConferenceModelInitializer
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
{
protected override void Seed(ConferenceContext context)
{
context.Sessions.Add(
new Session()
{
Title = "I Want Spaghetti",
Abstract = "The Life and times of a spaghetti lover",
Speaker = context.Speakers.Add(
new Speaker()
{
Name = "Jon Pepe",
EmailAddress = "jon#asfdasd.com"
})
});
context.SaveChanges();
}
}
}
ConferenceContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
}
Thank you!
replace:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
with:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Speaker> Speakers { get; set; } //since you are referencing the speaker class here
}
I keep getting this error, usually it has something to do with a using statement, but I think I might have messed something up or there is a using statement that I missed. And now I don't know what it is. Seen other people with the same question but finding out what using statement to use. Tried every Entity Framework statement but no other ones seem to be needed.
'BFProj2.Models.ContextModel' does not contain a definition for 'SaveChanges' and no extension method 'SaveChanges' accepting a first argument of type 'BFProj2.Models.ContextModel' could be found (are you missing a using directive or an assembly reference?)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using BFProj2.DAL;
namespace BFProj2.DAL
{
[Table("DataPlacer")]
public partial class DataPlacer : IEntity
{
public int csvId { get; set; }
[Required]
public string csvcolumn { get; set; }
}
public class IEntity
{
public int Id;
}
}
Repository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BFProj2.Models;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
namespace BFProj2.DAL
{
public class DCResultsRepository : IRepository<DataPlacer>
{
ContextModel _DataPlacerContext;
public DCResultsRepository()
{
_DataPlacerContext = new ContextModel();
}
public IEnumerable<DataPlacer> List
{
get
{
return _DataPlacerContext.DataPlacer;
}
}
public void Add(DataPlacer entity)
{
//TODO: Saknas usingsats som gör att SaveChanges inte fungerar.
_DataPlacerContext.DataPlacer.Add(entity);
_DataPlacerContext.SaveChanges();
}
public void Delete(DataPlacer entity)
{
_DataPlacerContext.DataPlacer.Remove(entity);
_DataPlacerContext.SaveChanges();
}
public void Update(DataPlacer entity)
{
_DataPlacerContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
_DataPlacerContext.SaveChanges();
}
public DataPlacer FindById(int Id)
{
var result = (from r in _DataPlacerContext.DataPlacer
where r.Id == Id
select r).FirstOrDefault();
return result;
}
}
IRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Core.Objects;
namespace BFProj2.DAL
{
interface IRepository<T> where T:IEntity
{
IEnumerable<T> List { get; }
void Add(T entity);
void Delete(T entity);
void Update(T entity);
T FindById(int Id);
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
namespace BFProj2.Models
{
public class ContextModel
{
//public object _DataPlacerContext { get; set; }
public List<DAL.DataPlacer> DataPlacer { get; set; }
}
}
you need to inherit from DbContext as shown below :-
public class ContextModel : DbContext
{
//public object _DataPlacerContext { get; set; }
public List<DAL.DataPlacer> DataPlacer { get; set; }
}
and make sure you have given reference of EntityFramework.dll in your project