Error 1 Error 2 on Conference MVC Tutorial - c#

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
}

Related

How to put select query in a list in C#? I get an error

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

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint on my asp.net app

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!

Doesn't contain definition for 'Books'

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
{
}

Visual Studio 2013 not recognizing reference to my new Model?

I'm working on an ASP.Net application. For one part of this, I have particular models stored in their own folder:
I have a reference to my Models/Default/ folder in one of my CustomControls: using Project.Models.Default; However, when I try to make a reference in my CustomControl YearsOfService to my default Model of Years_Of_Service, Visual Studio (2013) is not picking up either my Years_Of_Service or Years_Of_Service_Data model with my Models/Default/ folder:
Anyone have any ideas why this is happening?
EDIT:
Years_Of_Service.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PROJECT.Models
{
public class YearsOfService
{
public string Year { get; set; }
public decimal ServiceCredited { get; set; }
public decimal Salary { get; set; }
public string CoveredEmployer { get; set; }
}
}
Years_Of_Service_Data.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PROJECT.Models
{
public class YearsOfServiceData
{
public List<YearsOfService> YearsOfService { get; set; }
}
}
You currently have:
namespace PROJECT.Models
But this should also contain Default like this:
namespace PROJECT.Models.Default
So, it should end up like this:
namespace PROJECT.Models.Default
{
public class YearsOfServiceData
{
public List<YearsOfService> YearsOfService { get; set; }
}
}
Finally, you may want to keep your file names and class names the same otherwise it can get very confusing! So, stick with either Years_Of_Service_Data or YearsOfServiceData in both file and class name.
The classes contained in those files are just in the wrong namespace. Specify the correct one like this:
namespace XXXX.Models.Default
{
public class YearsOfService
{
//Snip
}
}
Alternatively, refer to them with their namespace as XXXX.Models.YearsOfService

add item into List<string> from another class in c#

I have 3 class. Those are places.cs, onePlace.cs and placestovisit.cs.
placestovisit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class placestovisit
{
public bool IsDataLoaded { get; set; }
public onePlace sunamganj { get; set; }
public static string basePlaces = "Assets/Places/";
private string baseTanguar = basePlaces + "Tanguar/";
private string baseBaruni = basePlaces + "Baruni/";
public void LoadData()
{
sunamganj = createSunamganj();
IsDataLoaded = true;
}
private onePlace createSunamganj()
{
onePlace data = new onePlace();
data.Items.Add(new places()
{
ID = "0",
Title = "Tanguar Haor",
shortDescription="Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District.",
itemImage = baseTanguar + "1.jpg",
FullDescription = "Tanguar Haor (Lowlaying marsh) is a complex landscape of over 46 marshes, 30 km Northwest of Sunamgonj District. The marshes are inter connected with one another through narrow Channels but merge into a single large water body during monsoon. The aquatic vegetation and less disturbance from the human are instrument to invite a large variety of waterfowl specially winter migrant ducks that congregates in thousands. Resident and local migrant, raptor, waders and passerine birds made the area as one of the Asia's most potential birding place. Tanguar Haor is listed as a Ramsar site under the Ramsar Convention in 2000."
});
}
}
onePlace.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class onePlace
{
public string Title { get; set; }
public List<places> Items { get; set; }
public onePlace()
{
Items = new List<places>();
}
}
}
places.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunamganj.ViewModels
{
public class places
{
public string ID { get; set; }
public string Title { get; set; }
public string shortDescription { get; set; }
public string FullDescription { get; set; }
public string itemImage { get; set; }
public List<string>Gallery { get; set; }
}
}
I want to add item into Gallery from placestovisit class. For that what to do?
Actually I want to add one photo gallery for each object. But I am not so much good in OOP. At this moment can I go with this concept or need to change the concept. If I can go with this one then how can I add item into Gallery from placestovisit class?
Gallery is just a property of your places class, and you can add items by accessing that property via an instance of places class.
One thing you should remember that the properties of reference types are null by default, so you need to initialize them.You can do that in your constructor:
public class places
{
public places()
{
Gallery = new List<string>();
}
}
Then you can add new items to your list like:
var plc = new places() { /* set the properties */ }
plc.Gallery.Add("new gallery");

Categories