This will be a long question, sorry. But it was necessary to unravel the logic.
This entity has all columns in DB:
public partial class Institution
{
public int? Id { get; set; }
public string? District { get; set; }
public string? InstitutionCode { get; set; }
public string? InstitutionName { get; set; }
public string? DemolitionStatus { get; set; }
public string? ReinforcementStatus { get; set; }
public string? BuildingOwnerStatus { get; set; }
public string? BuildingOwnerInstitution { get; set; }
public string? ClosureStatus { get; set; }
public string? ActivityStatus { get; set; }
public string? ETStatus { get; set; }
public int? ETPhase1 { get; set; }
public int? ETPhase2 { get; set; }
public int? ETPhase3 { get; set; }
public string? InfrastructureStatus { get; set; }
public string? InfrastructureScope { get; set; }
public string? InfrastructureInfo { get; set; }
public string? InfrastructureScopeOut { get; set; }
public string? IAccessStatus { get; set; }
public string? IAccessType { get; set; }
public string? ComputerClassStatus { get; set; }
public int? ComputerClassNumber { get; set; }
public int? PCNumber { get; set; }
public string? ComputerClassScope { get; set; }
public int? ETNeed { get; set; }
}
I have defined a model for columns containing ET so that all columns are not processed since I will only show the user data related to ET.
public class ETModel
{
public int? Id { get; set; }
public string? District { get; set; }
public string? InstitutionCode { get; set; }
public string? InstitutionName { get; set; }
public string? ActivityStatus { get; set; }
public string? ETStatus { get; set; }
public int? ETPhase1 { get; set; }
public int? ETPhase2 { get; set; }
public int? ETPhase3 { get; set; }
public int? ETNeed { get; set; }
}
Then, I defined a view model with a member of the list type, as I will return two lists to the user. I edited this view model to ETmodel.
public class ETListVM
{
public List<ETModel> ETyes { get; set; }
public List<ETModel> ETnone { get; set;}
}
I instantiated the view model in the controller. I have defined two variables of list type. But I'm having trouble filling out these lists. I can fill it with the Institutions entity, but this time I'm getting away from my purpose. I am using all columns. My goal is to use less resources using the ETModel.
public IActionResult Index(string district)
{
ETListVM vm= new ETListVM();
var ETyesList = c.**XXX**
.Where(p => p.District == district && p.ETStatus == "yes")
.ToList();
var ETnoneList = c.**XXX**
.Where(p => p.District == district && p.ETStatus == "none")
.ToList();
vm.ETyes = ETyesList;
vm.ETnone = ETnoneList;
return View();
}
If I write the Institutions entity where I specified as XXX, it works, but it does not accept the ETModel I want to use. Thank you for your patience and help.
Note: It only works if I define a new entity with related properties, but this time ETModel becomes meaningless.
You can't directly match two different models, you need to configure the mapping.
For example, you can use AutoMapper:
First, Install AutoMapper.Extensions.Microsoft.DependencyInjection NuGet Package and register it:
builder.Services.AddAutoMapper(typeof(Program));
Then, Create a class inherited from Profile to determine the mapping relationship:
public class UserProfile: Profile
{
public UserProfile()
{
CreateMap<Institution, ETModel>();
}
}
And in controller:
public IActionResult Index(string district)
{
ETListVM vm = new ETListVM();
var ETyesList = _context.Institution.Where(p => p.District == district && p.ETStatus == "yes").ToList();
var ETnoneList = _context.Institution.Where(p => p.District == district && p.ETStatus == "none").ToList();
List<ETModel> ETyes = new List<ETModel>();
ETyes = _mapper.Map<List<ETModel>>(ETyesList);
List<ETModel> ETnone = new List<ETModel>();
ETnone = _mapper.Map<List<ETModel>>(ETnoneList);
vm.ETyes = ETyes;
vm.ETnone = ETnone;
return View();
}
Related
Entity is:
public partial class Persons
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Surname { get; set; }
public string? Number { get; set; }
public string? Address { get; set; }
public string? PublicId { get; set; }
public string? FatherName { get; set; }
public string? MotherName { get; set; }
}
Also Model is:
public partial class OnlyPrivateProp
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Surname { get; set; }
}
And controller:
public class DemoController : Controller
{
_context c;
public DemoController(_context c)
{
this.c = c;
}
public IActionResult Index()
{
ET model= new ET();
var select = ..............
return View();
}
}
I dont want to use all data to display only three colunms. So I defined a model has three prop. But I cant pass data to model and cant select data and cant send controller.
You could create different ViewModel for different Views
The entities models are mapped to the tables in your database,you could check the documents related with EFCore
For your requirement,you could fill the viewmodel and pass the value to your View as below:
[Table("SomeTable")]
public class SomeEntity
{
public int Id { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
...........
}
public class ViewModel
{
public string Prop1 { get; set; }
public string Prop3 { get; set; }
}
public IActionResult SomeAction()
{
...........
var vmlist = _context.SomeEntity.Select(x => new ViewModel{ Prop1 = x.Prop1, Prop3 = x.Prop3 }).ToList();
return View(vmlist);
}
And the documents related with MVC
am getting a Enumerable Extensions join is inaccessible due to its protection level error. I am using EF Core for database connections. How to perform joins using LINQ ??
var seatBookings =(
from sb in Context.SeatBookings
join bd in Context.BookingDetails on sb.BookingId
equals bd.Id
where bd.ShowId == showId
select sb
).ToList();
public partial class SeatBookings
{
public int Id { get; set; }
public int? BookingId { get; set; }
public int SeatNumber { get; set; }
public BookingDetails Booking { get; set; }
}
public partial class BookingDetails
{
public BookingDetails()
{
SeatBookings = new HashSet<SeatBookings>();
}
public int Id { get; set; }
public int ShowId { get; set; }
public string Email { get; set; }
public string MobileNumber { get; set; }
public int TheaterId { get; set; }
public int BookedSeatsCount { get; set; }
public ShowDetails Show { get; set; }
public ICollection<SeatBookings> SeatBookings { get; set; }
}
Please look at my sample code below:
public class LoginModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class RegisterModel
{
[Key]
public int RegisterId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
}
There are many records in the cart table added by many users.
But i want to show the own record of a user from the cart table if he is logged in..how can I do this??
You have to insert a foreign-key property to your Cart class:
public class UserModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
public virtual UserModel User { get; set; } // <-- added
}
Then you can use LINQ to query the Cart-items for a specific user:
var cartItems = dbContext.Cart.Where(a => a.User == loggedInUser);
var query = from a in db.Pages
where a.title.Contains(myTitle)
select a;
var item=query.FirstOrDefault();
if(item!=null)
return View(item);
else
return View("NotFound");
Should T be a for example Customer or CustomerViewModel ?
The annotations bound to Mvc namespace are on the ListViewModel so actually I could pass the Customer object. What do you think?
public class ListViewModel<T>
{
[Required(ErrorMessage="No item selected.")]
public int[] SelectedIds { get; set; }
public IEnumerable<T> DisplayList { get; set; }
}
UPDATE
[HttpGet]
public ActionResult Open()
{
IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();
OpenTestplanListViewModel viewModel = new OpenTestplanListViewModel(testplans);
return PartialView(viewModel);
}
public class OpenTestplanListViewModel
{
public OpenTestplanListViewModel(IEnumerable<Testplan> testplans)
{
var testplanViewModels = testplans.Select(t => new TestplanViewModel
{
Name = string.Format("{0}-{1}-{2}-{3}", t.Release.Name, t.Template.Name, t.CreatedAt, t.CreatedBy),
TestplanId = t.TestplanId,
});
DisplayList = testplanViewModels;
}
[Required(ErrorMessage = "No item selected.")]
public int[] SelectedIds { get; set; }
public string Name { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; private set; }
}
public class TestplanViewModel
{
public int TestplanId { get; set; }
public string Name { get; set; }
}
public class Testplan
{
public int TestplanId { get; set; }
public int TemplateId { get; set; }
public int ReleaseId { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public Template Template { get; set; }
public Release Release { get; set; }
}
T should ideally be a view model. Having a view model referencing domain models is some kind of a hybrid view model, not a real one. But if you think that in this specific case the domain model will be exactly the same as the view model then you could keep it as well.
I can't understand what i'm doing wrong. Every time I'm getting this error:
The entity or complex type 'BusinessLogic.CompanyWithDivisionCount' cannot be constructed in a LINQ to Entities query.
I need to get info from 'Company' table and divisions count of each company from 'Division' table, and then make PagedList. Here is my 'Company' table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using BusinessLogic.Services;
using BusinessLogic.Models.ValidationAttributes;
namespace BusinessLogic.Models
{
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
}
Here is my domain model:
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
public class CompanyWithDivisionCount: Company // I'm using this
{
public int DivisionCount { get; set; }
}
Here is my controller:
public ActionResult CompaniesList(int? page)
{
var pageNumber = page ?? 1;
var companies = companyService.GetCompaniesWithDivisionsCount2();
var model = companies.ToPagedList(pageNumber, PageSize);
return View(model);
}
And here is my service part:
public IQueryable<CompanyWithDivisionCount> GetCompaniesWithDivisionsCount2()
{
return (from c in dataContext.Companies.AsQueryable()
select new CompanyWithDivisionCount
{
Id = c.Id,
Name = c.Name,
Status = c.Status,
EffectiveDate = c.EffectiveDate,
URL = c.URL,
EAP = c.EAP,
EAPCredentials = c.EAPCredentials,
Comments = c.Comments,
DivisionCount = (int)dataContext.Divisions.Where(b => b.CompanyName == c.Name).Count()
});
}
}
Thanks for help!!!
Creator of PagedList here. This has nothing to do with PagedList, but rather is an Entity Framework issue (I'm no expert on Entity Framework, so can't help you there). To confirm that this is true, write a unit test along the following lines:
[Test]
public void ShouldNotThrowAnException()
{
//arrange
var companies = companyService.GetCompaniesWithDivisionsCount2();
//act
var result = companies.ToList();
//assert
//if this line is reached, we win! no exception on call to .ToList()
}
I would consider changing you data model if possible so that instead of relating Companies to Divisions by name strings, instead use a properly maintained foreign key relationship between the two objects (Divisions should contain a CompanyID foreign key). This has a number of benefits (including performance and data integrity) and will almost certainly make your life easier moving forward if you need to make further changes to you app (or if any company ever decides that it may re-brand it's name).
If you create a proper foreign key relationship then your domain model could look like
public class Company
{
...
public virtual ICollection<Division> Divisions{ get; set; }
public int DivisionCount
{
get
{
return this.Divisions.Count()
}
}
...
}