LINQ query not translated correctly to the database - asp.net-mvc

I'm working on a MVC Web Site and as i'm newbie in mvc i'm facing some issues. This one is realy weird and have been bothering me for a while. I'm using LINQ to make my queries and some of then were realy, realy slow.
Then i opened SQL Server Profiler to look for the queries on a closer way. I just noted that my LINQ queries are being sent to the database without the where clause and that is making then to take a long time to be executed.
Now i'll post relevant part of code to see if u guys can get something wrong with that.
Model
[Table("tblSolicitacao")]
public partial class ChamadosViewModel
{
[Key]
public int Nsu { get; set; }
[Required(ErrorMessage = "*")]
public int IdAutor { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Assunto")]
public string NomeDaSolicitacao { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Descrição")]
public string Descricao { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Grupo")]
public string Grupo { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Atividade")]
public string Atividade { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Prioridade")]
public string Prioridade { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.DateTime, ErrorMessage = "Formato de Data Inválido")]
public Nullable<System.DateTime> DataPretendidaPeloAutor { get; set; }
public Nullable<bool> AcompanharViaEmail { get; set; }
public Nullable<int> IdAnalistaDesignado { get; set; }
public string Complexidade { get; set; }
public Nullable<System.DateTime> DataPrevistaPeloAnalista { get; set; }
public Nullable<int> SubordinacaoDeSolicitacao { get; set; }
public string COD_FORNECEDOR { get; set; }
public Nullable<decimal> TOLERANCIA { get; set; }
public string DESC_COND_PGTO { get; set; }
public string FILIAL_FATURAR { get; set; }
public string FILIAL_ENTREGA { get; set; }
public string FILIAL_COBRANCA { get; set; }
public string MOTIVO_COMPRA { get; set; }
public Nullable<int> TIPO_SOLICITACAO { get; set; }
public string FORMA_PGTO { get; set; }
public string MOTIVOCHAMADO { get; set; }
public Nullable<int> TEMPORESOLUCAO { get; set; }
public string CodigoRateioFilial { get; set; }
public string CodigoRateioCentroCusto { get; set; }
public Nullable<System.DateTime> DataSolicitacao { get; set; }
[NotMapped]
public string NomeAutor { get; set; }
[NotMapped]
public string NomeAnalista { get; set; }
public IEnumerable<genericoGruposViewModel> Grupos { get; set; }
[NotMapped]
public List<ListItem> Transitos { get; set; }
public List<string> Complexidades { get; set; }
public IEnumerable<genericoGrupoAtividadeViewModel> Atividades { get; set; }
public IEnumerable<genericoPrioridadeViewModel> Prioridades { get; set; }
public IEnumerable<ColaboradorViewModel> Usuarios { get; set; }
[NotMapped]
IEnumerable<ColaboradorViewModel> AnalistasDesignados { get; set; }
}
Controller
ChamadosViewModel ChamadoDetalhe = new ChamadoDetalhe();
ChamadoDetalhe = _dbHelpDesk.Chamados
.ToList()
.Where(x => x.Nsu == NumeroChamado)
.Select(x => new ChamadosViewModel
{
Nsu = x.Nsu,
IdAutor = x.IdAutor,
NomeDaSolicitacao = x.NomeDaSolicitacao,
Descricao = x.Descricao,
Grupo = x.Grupo,
Atividade = x.Atividade,
Prioridade = x.Prioridade,
DataPretendidaPeloAutor = x.DataPretendidaPeloAutor,
AcompanharViaEmail = x.AcompanharViaEmail,
IdAnalistaDesignado = x.IdAnalistaDesignado,
Complexidade = x.Complexidade,
DataPrevistaPeloAnalista = x.DataPrevistaPeloAnalista,
SubordinacaoDeSolicitacao = x.SubordinacaoDeSolicitacao,
COD_FORNECEDOR = x.COD_FORNECEDOR,
TOLERANCIA = x.TOLERANCIA,
DESC_COND_PGTO = x.DESC_COND_PGTO,
FILIAL_FATURAR = x.FILIAL_FATURAR,
FILIAL_ENTREGA = x.FILIAL_ENTREGA,
FILIAL_COBRANCA = x.FILIAL_COBRANCA,
MOTIVO_COMPRA = x.MOTIVO_COMPRA,
TIPO_SOLICITACAO = x.TIPO_SOLICITACAO,
FORMA_PGTO = x.FORMA_PGTO,
MOTIVOCHAMADO = x.MOTIVOCHAMADO,
TEMPORESOLUCAO = x.TEMPORESOLUCAO,
CodigoRateioFilial = x.CodigoRateioFilial,
CodigoRateioCentroCusto = x.CodigoRateioCentroCusto,
DataSolicitacao = x.DataSolicitacao
}
)
.Single()
and thats the select that went to the database
SELECT
[Extent1].[Nsu] AS [Nsu],
[Extent1].[IdAutor] AS [IdAutor],
[Extent1].[NomeDaSolicitacao] AS [NomeDaSolicitacao],
[Extent1].[Descricao] AS [Descricao],
[Extent1].[Grupo] AS [Grupo],
[Extent1].[Atividade] AS [Atividade],
[Extent1].[Prioridade] AS [Prioridade],
[Extent1].[DataPretendidaPeloAutor] AS [DataPretendidaPeloAutor],
[Extent1].[AcompanharViaEmail] AS [AcompanharViaEmail],
[Extent1].[IdAnalistaDesignado] AS [IdAnalistaDesignado],
[Extent1].[Complexidade] AS [Complexidade],
[Extent1].[DataPrevistaPeloAnalista] AS [DataPrevistaPeloAnalista],
[Extent1].[SubordinacaoDeSolicitacao] AS [SubordinacaoDeSolicitacao],
[Extent1].[COD_FORNECEDOR] AS [COD_FORNECEDOR],
[Extent1].[TOLERANCIA] AS [TOLERANCIA],
[Extent1].[DESC_COND_PGTO] AS [DESC_COND_PGTO],
[Extent1].[FILIAL_FATURAR] AS [FILIAL_FATURAR],
[Extent1].[FILIAL_ENTREGA] AS [FILIAL_ENTREGA],
[Extent1].[FILIAL_COBRANCA] AS [FILIAL_COBRANCA],
[Extent1].[MOTIVO_COMPRA] AS [MOTIVO_COMPRA],
[Extent1].[TIPO_SOLICITACAO] AS [TIPO_SOLICITACAO],
[Extent1].[FORMA_PGTO] AS [FORMA_PGTO],
[Extent1].[MOTIVOCHAMADO] AS [MOTIVOCHAMADO],
[Extent1].[TEMPORESOLUCAO] AS [TEMPORESOLUCAO],
[Extent1].[CodigoRateioFilial] AS [CodigoRateioFilial],
[Extent1].[CodigoRateioCentroCusto] AS [CodigoRateioCentroCusto],
[Extent1].[DataSolicitacao] AS [DataSolicitacao]
FROM [dbo].[tblSolicitacao] AS [Extent1]
Do you guys can imagine a reason for this where clause to have been omited ? Maybe something on my model class ?
Thanks for the support.

The ToList call brings the entire result set into memory and then you are performing the where, try the following:
dbHelpDesk.Chamados
.Where(x => x.Nsu == NumeroChamado)
.ToList()
.Select(x => new ChamadosViewModel ...

You used .ToList() before the .Where(.... .ToList() will grab the whole table in your situation. Simply remove that from your query and you should be good.

Related

How to insert an item into the collection with ef core

It's a class where i need to add item in Subtasks with Ef Core. Have no idea how to do it. Please help!
public class Do
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public string Executors { get; set; }
public DoStatus Status { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
[Required]
public int Plan { get; set; }
public int Fact { get; set; }
public DateTime? Finished { get; set; }
public virtual ICollection<Do> SubTasks { get; set; } = new List<Do>();
}
you need to learn about the recursive CTE relationship
for the date configure there with Api
builder.Property(p => p.Created).HasDefaultValueSql("(newid())")
public class Task
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public string Executors { get; set; }
public DoStatus Status { get; set; }
public DateTime Created { get; set; };
[Required]
public int Plan { get; set; }
public int Fact { get; set; }
public DateTime? Finished { get; set; }
public int DoId { get; set; } // id parent
public virtual List<Task> SubTasks { get; set; };
}
var id = 1 // id Do
var subTasks = db.Task.include(s => s.SubTasks).where(s => e.DoId = id).ToList()

Country and City Dropdown in ASP.NET Core MVC with db-first approach

I know this question might be asked so many times, I tried a lot to find the answer and ultimately I am throwing it here if some one can help me.
I am doing a project in ASP.NET Core MVC with a database-first approach. I have a registration form where I need to populate Country and City dropdowns to fill with data coming in through WeCareConext class.
In my controller I am doing this:
[HttpGet]
public IActionResult Register()
{
CompanyEditViewModel model = new CompanyEditViewModel();
var fromDatabaseEF = new SelectList(_context.Country.ToList(), "CountryId", "NameEn");
ViewData["CompanyRegister"] = fromDatabaseEF;
return View(model);
}
My Country model:
public partial class Country
{
public Country()
{
City = new HashSet<City>();
Currency = new HashSet<Currency>();
HolidayType = new HashSet<HolidayType>();
Holidays = new HashSet<Holidays>();
Province = new HashSet<Province>();
StaffInfo = new HashSet<StaffInfo>();
}
public int CountryId { get; set; }
public string NameAr { get; set; }
public string NameEn { get; set; }
public string NameFr { get; set; }
public string IsoCode2 { get; set; }
public string IsoCode3 { get; set; }
public string RegionAr { get; set; }
public string Region { get; set; }
public byte? PostcodeRequired { get; set; }
public bool? IsActive { get; set; }
public byte? IsAvailable { get; set; }
public string MobileMask { get; set; }
public byte? IsDeleted { get; set; }
public int? BaseCharges { get; set; }
public int? MobileNumberLength { get; set; }
public string CountryCode { get; set; }
public byte[] IconImage { get; set; }
public string PickerListAr { get; set; }
public string PickerListEn { get; set; }
public string PickerListFr { get; set; }
public virtual ICollection<City> City { get; set; }
public virtual ICollection<Currency> Currency { get; set; }
public virtual ICollection<HolidayType> HolidayType { get; set; }
public virtual ICollection<Holidays> Holidays { get; set; }
public virtual ICollection<Province> Province { get; set; }
public virtual ICollection<StaffInfo> StaffInfo { get; set; }
}
My CompanyEditViewModel class:
public class CompanyEditViewModel
{
[Display(Name = "Company Number")]
public string CompanyId { get; set; }
[Required]
[Display(Name = "Company Name")]
[StringLength(75)]
public string Name { get; set; }
[Required]
[Display(Name = "Country")]
public string CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
[Required]
[Display(Name = "City")]
public string SelectedCityCode { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
Unfortunately, this returns an error:
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
I am trying different approaches but not solving my issue. Can anyone suggest some code which can help me and I can also select country and then populate city dropdown according to the CountryID without page reload ? Thanks in advance.

Object reference error when getting data from database

My portal has worked fine for several years but nowadays I have problems with my some codes. I want to update my code but at the first step I have problems with login page. when I use FirstOrDefault I got error on object reference while the list is filled and contains 1 user.
int g = db.sp_GetUserData_ByUserName(model.UserName.Trim()).Count();
//it shows 1
OSUserData userData1 = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
I didn't change this code and It works perfectly on the portal. However, I can't run it on my development server.
I checked again and I found that OSUserData constructor throws exception : Enumeration yielded no result. this is my class code :
public OSUserData()
{
this.OSUploadedFilesMultipleUsers = new HashSet<OSUploadedFilesMultipleUser>();
this.OSSalaryLists = new HashSet<OSSalaryList>();
this.OSUploadedFiles = new HashSet<OSUploadedFile>();
}
public int Id { get; set; }
public string Address { get; set; }
public string BranchCode { get; set; }
public string BranchParentNationalCode { get; set; }
public string CitName { get; set; }
public string City { get; set; }
public string CompanyName { get; set; }
public string CouName { get; set; }
public string Country { get; set; }
public string FaxNo { get; set; }
public string FollowCode { get; set; }
public string Hozeh { get; set; }
public Nullable<bool> IsBranch { get; set; }
public string LoginStatus { get; set; }
public string NationalCode { get; set; }
public string NewEconomicNo { get; set; }
public string Oldeconomicno { get; set; }
public string PostalCode { get; set; }
public string ProIdTTMS { get; set; }
public string ProName { get; set; }
public string Provision { get; set; }
public string RegistrationNo { get; set; }
public string State { get; set; }
public string TaxOfficeCode { get; set; }
public string TaxPayerType { get; set; }
public string TelCode { get; set; }
public string TelNo { get; set; }
public string TprId { get; set; }
public string UserName { get; set; }
public bool Validate { get; set; }
public bool Disabled { get; set; }
public string OwnerShipTypeDesc { get; set; }
public Nullable<byte> OwnerShipTypeCode { get; set; }
public bool Processed { get; set; }
public bool CheckedUser { get; set; }
public bool Blocked { get; set; }
public virtual ICollection<OSUploadedFilesMultipleUser> OSUploadedFilesMultipleUsers { get; set; }
public virtual ICollection<OSSalaryList> OSSalaryLists { get; set; }
public virtual ICollection<OSUploadedFile> OSUploadedFiles { get; set; }
You are trying to add to a null/unreferenced/not initialized object/list. Initialize first the list
List<OSUserData> userData1 = new List<OSUserData>();
Then add it
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
userData1.Add(new OSUserData{
Prop1 = user.Prop1,
Prop2 = user.Prop2,
......
});
Or if you only want one user, just make it var
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();

Automapper with nested entity not working

I have two classes which are mentioned below. I am trying to map those through Auto Mapper but it is not working.
public class VMTemplates
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public System.DateTime TimeStamp { get; set; }
public virtual ICollection<VMTemplateGroup> VMTemplateGroup { get; set; }
}
public VMTemplateViewModel()
{
VMTemplateGroup = new List<VMTemplateGroupViewModel>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
[Required(ErrorMessage = "Please Upload File")]
[Display(Name = "Upload File")]
[ValidateFile]
public HttpPostedFileBase TemplateUpload { get; set; }
public System.DateTime TimeStamp { get; set; }
public List<VMTemplateGroupViewModel> VMTemplateGroup { get; set; }
I am using this code to map them
confi.CreateMap<VMTemplateViewModel, VMTemplates>().ReverseMap();
confi.CreateMap<VMTemplateGroupViewModel, VMTemplateGroup>().ReverseMap();
calling code
public VMTemplates GetVMTemplateById(int id)
{
return DataContext.VMTemplates.Include("VMTemplateGroup").Where(a => a.Id == id).FirstOrDefault();
}
This is where exception happens. I get stack overflow exception
public VMTemplateViewModel GetVMTemplateById(int templateId)
{
var result = _vmTemplateRepository.GetVMTemplateById(templateId);
return _autoMapperService.MapEntity<VMTemplateViewModel>(result);
}

EF Code First not generating join tables for n:m relationships

I've been using this tutorial as a guide for code first n:m. I usually go with db first but for a school project I have to use code first...
My 2 classes are as follows:
public class Product
{
public Product()
{
Stocks = new HashSet<Stock>();
ServingUnits = new HashSet<Unit>();
Orders = new HashSet<Order>();
}
public int ProductId { get; set; }
[StringLength(128, MinimumLength = 1)]
[Required]
public string Title { get; set; }
[StringLength(512, MinimumLength = 1)]
public string Description { get; set; }
public int ExperationPeriod { get; set; }
public byte[] Image { get; set; }
[Required]
public DateTime DateCreated { get; set; }
//foreign keys
[Required]
public int StockUnitId { get; set; }
[Required]
public string CreatedById { get; set; }
[Required]
public int ProductStateId { get; set; }
[Required]
public int ProductTypeId { get; set; }
//navigation properties
[ForeignKey("StockUnitId")]
public virtual Unit StockUnit { get; set; }
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }
[ForeignKey("ProductStateId")]
public virtual ProductState ProductState { get; set; }
[ForeignKey("ProductTypeId")]
public virtual ProductType ProductType { get; set; }
public virtual ICollection<Stock> Stocks { get; set; }
public virtual ICollection<Unit> ServingUnits { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
and the other:
public class Unit
{
public Unit()
{
Orders = new HashSet<Order>();
ProductsStock = new HashSet<Product>();
ProductsServe = new HashSet<Product>();
}
public int UnitId { get; set; }
[StringLength(255, MinimumLength = 1)]
[Required]
public string Title { get; set; }
[StringLength(128, MinimumLength = 1)]
public string ShortName { get; set; }
public string Description { get; set; }
[Required]
public double BasisFactor { get; set; }
[Required]
public DateTime DateCreated { get; set; }
//foreign keys
[Required]
public string CreatedById { get; set; }
//navigation properties
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }
public virtual ICollection<Product> ProductsStock { get; set; }
public virtual ICollection<Product> ProductsServe { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
But the join table doesn't exist in my database. Can anyone see what I'm doing wrong?
Thanks

Resources