DataAnnotations and ModelState.IsValid no working - c#

I have annotations in two models, the two are related, ModelState.IsValid returns false when there are annotations, delete annotations if it works without problem, anyone know why this happens?
Model 1:
namespace SifActivoFijo.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class AF_UbicacionActivoFijo
{
public long IdUbicacion { get; set; }
[Required(ErrorMessage = "1*")]
[Display(Name = "Codigo Centro de Costo")]
public string GN_CentroDeCosto_CodigoCentroDeCosto { get; set; }
[Required(ErrorMessage = "2*")]
[Display(Name = "Tercero")]
public string GN_Persona_CodigoPersona { get; set; }
//[Required(ErrorMessage = "3*")]
[Display(Name = "Codigo Activo")]
public string AF_ActivoFijo_CodigoActivoFijo { get; set; }
[Required(ErrorMessage = "4*")]
[Display(Name = "Contacto")]
public string Contacto { get; set; }
[Required(ErrorMessage = "5*")]
[Display(Name = "Direccion")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string Direccion { get; set; }
[Required(ErrorMessage = "6*")]
[Display(Name = "Telefono")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string Telefono { get; set; }
[Required(ErrorMessage = "7*")]
[Display(Name = "Celular")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public string Celular { get; set; }
[Required(ErrorMessage = "8*")]
[Display(Name = "Email")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Email { get; set; }
[Required(ErrorMessage = "9*")]
[Display(Name = "Responsable")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable { get; set; }
[Required(ErrorMessage = "10*")]
[Display(Name = "Documento")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable_documento { get; set; }
[Required(ErrorMessage = "11*")]
[Display(Name = "Telefono")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable_Telefono { get; set; }
[Required(ErrorMessage = "12*")]
[Display(Name = "Sucursal")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Sucursal { get; set; }
[Required(ErrorMessage = "13*")]
[Display(Name = "N° Contrato")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string NoContrato { get; set; }
[Required(ErrorMessage = "14*")]
[Display(Name = "Ciudad")]
public string GN_Nivel3_CodigoNivel3 { get; set; }
[Required(ErrorMessage = "15*")]
[Display(Name = "Fecha Inicial")]
public System.DateTime FechaInicial { get; set; }
public virtual GN_Nivel3 GN_Nivel3 { get; set; }
public virtual AF_ActivoFijo AF_ActivoFijo { get; set; }
public virtual GN_Persona GN_Persona { get; set; }
public virtual GN_CentroDeCosto GN_CentroDeCosto { get; set; }
}
}
Model 2:
namespace SifActivoFijo.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class AF_ActivoFijo
{
public AF_ActivoFijo()
{
this.AF_ConfiguracionActivoFijo = new HashSet<AF_ConfiguracionActivoFijo>();
this.AF_DepreciacionActivoFijo = new HashSet<AF_DepreciacionActivoFijo>();
this.AF_UbicacionActivoFijo = new HashSet<AF_UbicacionActivoFijo>();
this.AF_RevaluacionNIIF = new HashSet<AF_RevaluacionNIIF>();
}
[Required(ErrorMessage = "*1")]
[Display(Name = "Activo Fijo Principal")]
[RegularExpression(#"[A-Za-z_0-9 .#_-]*\.?[A-Za-z_0-9 .#_-]+", ErrorMessage = "**")]
public string CodigoActivoFijo { get; set; }
[Required(ErrorMessage = "*2")]
[Display(Name = "Grupo Contable")]
public string AF_GrupoContableAF_CodigoGrupoContableAF { get; set; }
[Required(ErrorMessage = "*3")]
[Display(Name = "Estado")]
public string ST_Estado_CodigoEstado { get; set; }
[Required(ErrorMessage = "*4")]
[Display(Name = "Grupo de Activo")]
public string AF_GrupoActivoFijo_CodigoGrupoAF { get; set; }
[Required(ErrorMessage = "*5")]
[Display(Name = "Producto")]
public string GN_Portafolio_CodigoPortafolio { get; set; }
[Display(Name = "Serial")]
[RegularExpression(#"[A-Za-z_0-9 .ñÑ#_-]*\.?[A-Za-z_0-9 .Ññ#_-]+", ErrorMessage = "**")]
public string Serial { get; set; }
[Display(Name = "Configurable")]
public bool SenConfigurable { get; set; }
[Required(ErrorMessage = "*6")]
[Display(Name = "Fecha de Activacion")]
public Nullable<System.DateTime> FechaActivacion { get; set; }
[Required(ErrorMessage = "*7")]
[Display(Name = "Costo")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
[DataType(DataType.Currency)]
public Nullable<double> Costo { get; set; }
[Required(ErrorMessage = "*8")]
[Display(Name = "IVA")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> ValorIva { get; set; }
[Required(ErrorMessage = "*9")]
[Display(Name = "Margen")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> PorcentajeMargen { get; set; }
[Display(Name = "Costo Activo")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> CostoActivo { get; set; }
[Display(Name = "Tiempo Contable")]
public Nullable<int> TiempoDepreciacionContable { get; set; }
[Display(Name = "Tiempo Fiscal")]
public Nullable<int> TiempoDepreciacionFiscal { get; set; }
[Display(Name = "Depreciable Individiual")]
public bool SenDepreciacionIndividual { get; set; }
[Display(Name = "Saldo Contable")]
public Nullable<double> SaldoADepreciar { get; set; }
[Required(ErrorMessage = "*10")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string DescripcionActivoFijo { get; set; }
[Display(Name = "Saldo Fiscal")]
public Nullable<double> SaldoAdepreciarFiscal { get; set; }
[Display(Name = "Depreciable")]
public bool SenDepreciable { get; set; }
[Required(ErrorMessage = "*11")]
[Display(Name = "Propietario")]
public string GN_Persona_CodigoPersona { get; set; }
public Nullable<double> SaldoNiif { get; set; }
public Nullable<int> VidaUtilNiif { get; set; }
public Nullable<System.DateTime> FechaReevaluacion { get; set; }
public virtual AF_GrupoActivoFijo AF_GrupoActivoFijo { get; set; }
public virtual AF_GrupoContableAF AF_GrupoContableAF { get; set; }
public virtual GN_Portafolio GN_Portafolio { get; set; }
public virtual ST_Estado ST_Estado { get; set; }
public virtual ICollection<AF_ConfiguracionActivoFijo> AF_ConfiguracionActivoFijo { get; set; }
public virtual ICollection<AF_DepreciacionActivoFijo> AF_DepreciacionActivoFijo { get; set; }
public virtual ICollection<AF_UbicacionActivoFijo> AF_UbicacionActivoFijo { get; set; }
public virtual ICollection<AF_RevaluacionNIIF> AF_RevaluacionNIIF { get; set; }
}
}
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AF_UbicacionActivoFijo ubicacion)
{
AF_UbicacionActivoFijo au = new AF_UbicacionActivoFijo {
IdUbicacion=ubicacion.IdUbicacion,
GN_CentroDeCosto_CodigoCentroDeCosto=ubicacion.GN_CentroDeCosto_CodigoCentroDeCosto,
GN_Persona_CodigoPersona=ubicacion.GN_Persona_CodigoPersona,
AF_ActivoFijo_CodigoActivoFijo=ubicacion.AF_ActivoFijo_CodigoActivoFijo,
Contacto=ubicacion.Contacto,
Direccion=ubicacion.Direccion,
Telefono=ubicacion.Telefono,
Celular=ubicacion.Celular,
Email=ubicacion.Email,
Responsable=ubicacion.Responsable,
Responsable_documento=ubicacion.Responsable_documento,
Responsable_Telefono=ubicacion.Responsable_Telefono,
Sucursal=ubicacion.Sucursal,
NoContrato=ubicacion.NoContrato,
GN_Nivel3_CodigoNivel3=ubicacion.GN_Nivel3_CodigoNivel3,
FechaInicial=ubicacion.FechaInicial
};
if (ModelState.IsValid)
{
db.Entry(au).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("confirm", "Home");
}
else
{
foreach (var modelStateValue in ViewData.ModelState.Values)
{
foreach (var error in modelStateValue.Errors)
{
//Use breakpoints and Let's check what it is in these properties
var errorMessage = error.ErrorMessage;
var exception = error.Exception;
}
}
}
ViewBag.GN_Nivel3_CodigoNivel3 = new SelectList(db.GN_Nivel3, "CodigoNivel3", "NombreNivel3", ubicacion.GN_Nivel3_CodigoNivel3);
ViewBag.GN_CentroDeCosto_CodigoCentroDeCosto = new SelectList(db.GN_CentroDeCosto, "CodigoCentroDeCosto", "NombreCentroDeCosto", ubicacion.GN_CentroDeCosto_CodigoCentroDeCosto);
return View(ubicacion);
}

Data annotations work as validations on models and when we do model.IsValid then all annotations are validated against the values we assign to model properties , it seems that any of your regular expression is not validating your assigned value.

Related

Error when registering a new client in the base using MVVM

Good morning everyone, I'm taking this "InvalidOperationException: The value of 'Customer.CustomerId' is unknown when trying to save changes.
" in my application when I try to save the client in the base to receive its ID to pass in the second item of the ViewModel.
I'm using Asp.Net Core 5
public class Cliente
{
[Display(Name = "Código")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClienteId { get; set; }
[Display(Name = "Nome")]
[StringLength(50)]
public string Nome { get; set; }
[Display(Name = "Fantasia")]
[StringLength(40)]
public string Fantasia { get; set; }
[Display(Name = "Inscrição Estadual")]
public string IE { get; set; }
[Display(Name = "CPF ou CNPJ")]
public string Cpf_Cnpj { get; set; }
[Display(Name = "Tipo Pessoa")]
public string Tipo_Pessoa { get; set; }
[Required(ErrorMessage = "Informe o seu endereço")]
[StringLength(100)]
[Display(Name = "Endereço")]
public string Endereco { get; set; }
[Display(Name = "Numero")]
public string Numero { get; set; }
[Display(Name = "Informe o seu Complemento")]
public string Complemento { get; set; }
[StringLength(50)]
public string Bairro { get; set; }
[Required(ErrorMessage = "Informe o seu CEP")]
[Display(Name = "CEP")]
[StringLength(10, MinimumLength = 8)]
public string Cep { get; set; }
[StringLength(30)]
[Display(Name = "Cidade")]
public string Cidade { get; set; }
[StringLength(30)]
[Display(Name = "Estado")]
public string Estado { get; set; }
[Display(Name = "Status")]
public bool Situacao { get; set; }
[Display(Name = "Segmento")]
public string Segmento { get; set; }
[Display(Name = "Porte")]
public string Porte { get; set; }
public ICollection<Contato> Contato { get; set; }
}
public class Contato
{
[Display(Name = "Código")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContatoId { get; set; }
[Display(Name = "Nome")]
[StringLength(50)]
public string Nome { get; set; }
[Required(ErrorMessage = "Informe o sobrenome")]
[Display(Name = "Sobrenome")]
[StringLength(40)]
public string Sobrenome { get; set; }
[Display(Name = "Cargo")]
public string Cargo { get; set; }
[Display(Name = "Setor")]
public string Setor { get; set; }
[Required(ErrorMessage = "Informe o seu Email")]
[StringLength(20)]
[Display(Name = "E-mail")]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "Informe o seu telefone")]
[StringLength(20)]
[Display(Name = "Telefone")]
public string Telefone { get; set; }
[Required(ErrorMessage = "Informe o seu Celular")]
[StringLength(20)]
public string Celular { get; set; }
[Display(Name = "Usuário")]
public int? UsuarioId { get; set; }
[ForeignKey("UsuarioId")]
public virtual Usuario Usuarios { get; set; }
public int? ClienteId { get; set; }
[ForeignKey("ClienteId")]
public virtual Cliente Clientes { get; set; }
}
ViewModel
public class ClienteViewModel
{
public Cliente cliente { get; set; }
public Contato contato { get; set; }
}
Controller
[HttpPost]
public IActionResult Cadastrar(ClienteViewModel clienteViewModel)
{
if (ModelState.IsValid)
{
Models.Cliente cliente = new Models.Cliente
{
Nome = clienteViewModel.cliente.Nome,
Tipo_Pessoa = clienteViewModel.cliente.Tipo_Pessoa,
Cpf_Cnpj = clienteViewModel.cliente.Cpf_Cnpj,
Fantasia = clienteViewModel.cliente.Fantasia,
IE = clienteViewModel.cliente.IE,
Porte = clienteViewModel.cliente.Porte,
Segmento = clienteViewModel.cliente.Segmento,
Cep = clienteViewModel.cliente.Cep,
Endereco = clienteViewModel.cliente.Endereco,
Numero = clienteViewModel.cliente.Numero,
Complemento = clienteViewModel.cliente.Complemento,
Bairro = clienteViewModel.cliente.Bairro,
Cidade = clienteViewModel.cliente.Cidade,
Estado = clienteViewModel.cliente.Estado,
Situacao = true
};
_clienteRespository.Cadastrar(cliente);
Contato contato = new Contato
{
Nome = clienteViewModel.contato.Nome,
Sobrenome = clienteViewModel.contato.Sobrenome,
Telefone = clienteViewModel.contato.Telefone,
Celular = clienteViewModel.contato.Celular,
Email = clienteViewModel.contato.Email,
Cargo = clienteViewModel.contato.Cargo,
Setor = clienteViewModel.contato.Setor,
ClienteId = cliente.ClienteId,
Clientes = cliente
};
Models.Usuario usuario = new Models.Usuario()
{
Nome = contato.Nome,
Sobrenome = contato.Sobrenome,
Email = contato.Email,
Telefone = contato.Celular,
Cargo = contato.Cargo,
Setor = contato.Setor,
PerfilId = _helpers.createPerfilSuperAdministradorCliente(cliente.ClienteId).PerfilClienteId,
Senha = contato.Email,
Status = true
};
_usuarioRespository.Cadastrar(usuario);
clienteViewModel.contato.UsuarioId = usuario.UsuarioId;
_clienteRespository.Cadastrar(cliente.ClienteId, contato);
return RedirectToAction(nameof(Index));
}
return View();
}
Repository
public void Cadastrar(Cliente cliente)
{
_context.Add(cliente);
_context.SaveChanges();
}
public void Cadastrar(int ClienteId, Contato contato)
{
contato.ClienteId = ClienteId;
_context.Add(contato);
_context.SaveChanges();
}
Thank you in advance for your help.
you have to fix ALL your repositories
public void Cadastrar(Cliente cliente)
{
_context.Set<Cliente>().Add(cliente);
_context.SaveChanges();
}
public void Cadastrar(int ClienteId, Contato contato)
{
contato.ClienteId = ClienteId;
_context.Set<Contato>.Add(contato);
_context.SaveChanges();
}

Why Database.SqlQuery is returning 0 rows?

I have used this
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails", InspectionReportID).ToList();
return List;
}
in a class that is inherited from DbContext
I am calling this function in a controller but List is empty. Database.SqlQuery returns 0 items even the procedure is returning data for the parameter i am providing to the function but not this.
Update:
alter PROCEDURE GetInspectionReportDetails
#InspectionReportID int=0
AS
BEGIN
Select ir.InspectionReportID
,ir.VelosiProjectNo
,ir.VelosiReportNo
,ir.Reference
,ir.PoNo
,ir.InspectionDate
,ir.IssueDate
,ir.InspectionPhase
,ir.InServiceInspection
,ir.NewInduction
,ir.HydrostaticTest
,ir.DimensionalCheck
,ir.ThicknessCheck
,ir.Patrom
,ir.Gvs
,ir.FinalOgraInspection
,ir.OmcClientRequirement
,ir.TankLorryRegistrationNo
,ir.TruckTractorManufacturerName
,ir.ClientName
,ir.Capacity
,ir.Omc
,ir.EngineNo
,ir.TankLorryDimension
,ir.ChassisNo
,ir.InspectionPlace
,ir.TankLorryEnginePower
,ir.CarriageName
,ir.Brakes
,ir.IsSatisfactory
,ir.Remarks
,ir.Rev
,ir.Description
,ir.Status
,u1.UserName as PeparedBy
,u2.UserName as CheckedBy
,u3.UserName as ApprovedBy
,u4.UserName as IssuedBy
From InspectionReport ir
Inner Join dbo.[User] u1
ON u1.UserID= ir.PeparedBy
Inner Join dbo.[User] u2
ON u2.UserID= ir.CheckedBy
Inner Join dbo.[User] u3
ON u3.UserID= ir.ApprovedBy
Inner Join dbo.[User] u4
ON u4.UserID= ir.IssuedBy
where ir.InspectionReportID= #InspectionReportID
This is the stored procedure that is called by the function.
This the class inpsectionreport;
namespace VAILCertificates.DAL.Entities
{
public class InspectionReport
{
//General Details
public int InspectionReportID { get; set; }
[Required]
[Display (Name= "Velosi Project No")]
public string VelosiProjectNo { get; set; }
[Display(Name = "Velosi Report No")]
public string VelosiReportNo { get; set; }
[Required]
public string Reference { get; set; }
[Required]
[Display(Name = "PO No")]
public string PoNo { get; set; }
[Required]
[Display(Name = "Inspection Date")]
public DateTime InspectionDate { get; set; }
[Required]
[Display(Name = "Issue Date")]
public DateTime IssueDate { get; set; }
//Inspection Phase
[Required]
[Display(Name = "Inspection Phase")]
public byte InspectionPhase { get; set; } //0= Before, 1= During, 2= Final
//Types Of Inspection
[Display(Name = "In Service Inspection")]
public bool InServiceInspection { get; set; }
[Display(Name = "New Induction")]
public bool NewInduction { get; set; }
[Display(Name = "Hydorstatic Test")]
public bool HydrostaticTest { get; set; }
[Display(Name = "Dimensional Check")]
public bool DimensionalCheck { get; set; }
[Display(Name = "Thickness Check")]
public bool ThicknessCheck { get; set; }
[Display(Name = "PATROM")]
public bool Patrom { get; set; }
[Display(Name = "GVS")]
public bool Gvs { get; set; }
[Display(Name = "Final OGRA Inspection")]
public bool FinalOgraInspection { get; set; }
[Display(Name = "OMC/Client Requirement")]
public bool OmcClientRequirement { get; set; }
//Details Of Tank Lorry
[Required]
[Display(Name = "Tank Lorry Registration Number")]
public string TankLorryRegistrationNo { get; set; }
[Required]
[Display(Name = "Truck Tractor Manufacturer Name")]
public string TruckTractorManufacturerName { get; set; }
[Required]
[Display(Name = "Client Name")]
public string ClientName { get; set; }
[Required]
[Display(Name = "Capacity")]
public string Capacity { get; set; }
[Required]
[Display(Name = "OMC")]
public string Omc { get; set; }
[Required]
[Display(Name = "Engine No")]
public string EngineNo { get; set; }
[Required]
[Display(Name = "Tank Lorry Dimension")]
public string TankLorryDimension { get; set; }
[Required]
[Display(Name = "Chassis Number")]
public string ChassisNo { get; set; }
[Required]
[Display(Name = "Inspection Place")]
public string InspectionPlace { get; set; }
[Required]
[Display(Name = "Tank Lorry (Engine Power)")]
public string TankLorryEnginePower { get; set; }
[Required]
[Display(Name = "Carriage Name")]
public string CarriageName { get; set; }
[Required]
public string Brakes { get; set; }
//ResultsofInspection
[Required]
[Display(Name = "Is Satisfactory?")]
public bool IsSatisfactory { get; set; }
//Remarks
[Required]
public string Remarks { get; set; }
//ApprovalSection
public string Rev { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int PeparedBy { get; set; }
public int CheckedBy { get; set; }
public int ApprovedBy { get; set; }
public int IssuedBy { get; set; }
//ReportStatus
public byte Status { get; set; } //0= Prepared 1= CheckedBy 2= ApprovedBy
}
}
You can also construct a DbParameter and supply it as a parameter value to your stored procedure:
var InspectionReportID= new SqlParameter("#InspectionReportID", 0);
var list = this.Database.SqlQuery<InspectionReport>("EXECUTE dbo.GetInspectionReportDetails #InspectionReportID",InspectionReportID).ToList();
It is important to parameterize any user input to protect against a SQL injection attack. You can include parameter placeholders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter.
Try changing the the sql statement, I feel the error is how you call the sql statement.
var list = this.Database.SqlQuery<InspectionReport>($"EXEC GetInspectionReportDetails {InspectionReportID}").ToList();
Try using this code:
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails #InspectionReportID", InspectionReportID).ToList();
return List;
}

Mapping ViewModel to related entities

I have a ViewModel with several properties (VM for multi-step wizard):
public class CallViewModel
{
[Key]
[Column(Order = 0)]
[HiddenInput(DisplayValue = false)]
public System.Guid CallID { get; set; }
[Required, Display(Name = "Call Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime CallDate { get; set; }
[Required, Display(Name = "Contract Number")]
public string Number { get; set; }
[Display(Name = "Date of Sampling"), DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime SampleActDate { get; set; }
[Display(Name = "Date of the Contract"), DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime ContractDate { get; set; }
[Required, Display(Name = "Cost Efficiency, %")]
public decimal CostEfficiency { get; set; }
[Required, Display(Name = "Document Type")]
public string CallName { get; set; }
//Representative
[Required, Display(Name = "Second Name")]
public string RepFamilyName { get; set; }
[Required, Display(Name = "First Name")]
public string RepFirstName { get; set; }
[Required, Display(Name = "Middle Name")]
public string RepMidName { get; set; }
[Required, Display(Name = "Position")]
public string RepPosition { get; set; }
[Required, Display(Name = "Document")]
public string DocType { get; set; }
[Required, Display(Name = "Phone (###) ###-##-##")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:(###) ###-##-##}")]
public string RepPhoneNumber { get; set; }
//Customer
[Required, Display(Name = "Judicial Status")]
public string JudicialStatus { get; set; }
[Required, Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Required, Display(Name = "Address")]
public string CustomerAddress { get; set; }
[Required, Display(Name = "TaxID")]
public string TaxID { get; set; }
[Display(Name = "BIC")]
public string BIC { get; set; }
[Required, Display(Name = "PHone Number (###) ###-##-##")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:(###) ###-##-##}")]
public string CustomerPhoneNumber { get; set; }
[Required, Display(Name = "OKPO")]
public int OKPO { get; set; }
[Required, Display(Name = "Account)]
public string CustomerBankAccount { get; set; }
[Required, Display(Name = "Bank Branch")]
public string BankBranch { get; set; }
[Required, Display(Name = "Bank Address")]
public string BranchAddress { get; set; }
[Display(Name = "Bank Code")]
public Nullable<int> BankCode { get; set; }
[Display(Name = "Cell Phone Number")]
public string MPhoneNumber { get; set; }
//Person
[Required, Display(Name = "Expert")]
//public string Exp { get; set; }
public Guid ExpID { get; set; }
[Required, Display(Name = "Affidavit Number")]
public int AffidavitNum { get; set; }
[Required, Display(Name = "Affidavit Date"),
DataType(DataType.Date)]
public System.DateTime AffidavitDate { get; set; }
public List<ItemClass> ItemsList { get { return _items; } }
private List<ItemClass> _items = new List<ItemClass>();
public class ItemClass
{ //Item
public Guid ItemID { get; set; }
[Required, Display(Name = "Item SubType")]
public Guid ItemSubtype { get; set; }
[Required, Display(Name = "Item Name")]
public string ItemName { get; set; }
[Required, Display(Name = "Producer")]
public string ItemProducer { get; set; }
[Required, Display(Name = "Quantity")]
public int ItemQty { get; set; }
[Display(Name = "Additionals")]
public string Additional { get; set; }
[Required, Display(Name = "Program Name")]
public string ProgramNameShort { get; set; }
[Required, Display(Name = "Calc Date")]
public string calcDate { get; set; }
[Required, Display(Name = "Calc Number")]
public string calcNum { get; set; }
}
}
I also have several entities with 1:n relationships, like
public partial class Call
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Call()
{
this.CallDetails = new HashSet<CallDetail>();
}
public System.Guid CallID { get; set; }
public System.DateTime CallDate { get; set; }
public System.Guid CustomerID { get; set; }
public string DocNumber { get; set; }
public int AffidavitNum { get; set; }
public System.DateTime AffidavitDate { get; set; }
public System.DateTime ContractDate { get; set; }
public int CallStatus { get; set; }
public string DocType { get; set; }
public Nullable<decimal> Cost_Efficiency { get; set; }
public System.DateTime SampleActDate { get; set; }
public string CallName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CallDetail> CallDetails { get; set; }
public virtual Customer Customer { get; set; }
}
and
public partial class CallDetail
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CallDetail()
{
this.Orders = new HashSet<Order>();
}
public System.Guid CallID { get; set; }
public System.Guid ItemID { get; set; }
public int ItemQty { get; set; }
public decimal ItemTestCost { get; set; }
public System.Guid ProgramID { get; set; }
public virtual Call Call { get; set; }
public virtual Item Item { get; set; }
public virtual Program Program { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Order> Orders { get; set; }
}
to name a few.
In [HttpPost] public ActionResult Create (CallViewModel callViewModel) method I should map the ViewModel to those entities. I know that Automapper is among the best ways to perform it, but still I need to understand the principles of correct mapping of VM and related entities (Automapper examples are welcome as well :) ), and especially how to deal with navigation properties (I'm mostly worried about ID properties). Could you please show the best (or template) practice to perform it? Please, be as detailed as possible.
Thanks in advance.
Take this example:
public class ModelClass
{
public Guid Id { get; set; }
public ChildModel ChildModel { get; set; }
}
public class ViewModelClass
{
public Guid Id { get; set; }
public ChildModel ChildModel { get; set; } = new ChildModel();
}
public class ChildModel
{
public Guid Id { get; set; }
}
If you want to map your viewmodel to your model you can do:
[HttpPost]
public ActionResult Create (CallViewModel callViewModel) {
var model = new ModelClass;
model.Id = callViewModel.Id;
model.ChildModel = callViewModel.ChildModel;
_context.Add(model);
_context.SaveChanges();
return RedirectToAction("Index");
}
For the use of automapper I suggest you read the AutoMapper docs :)

How to use a html select in MVC .net using Automapper? [duplicate]

This question already has answers here:
DropDownList in MVC 4 with Razor
(13 answers)
Closed 7 years ago.
client class :
public partial class Client
{
public Client()
{
this.Produits = new List<Produit>();
}
public int idClient { get; set; }
public string nom { get; set; }
public string prenom { get; set; }
public string Email { get; set; }
public int Tel { get; set; }
public virtual ICollection<Produit> Produits { get; set; }
}
produit class:
public partial class Produit
{
public int ProduitID { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public int Prix { get; set; }
public Nullable<int> client_id { get; set; }
public virtual Client client { get; set; }
}
view produit :
// POST: /Produit/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProduitID,Type,Description,Prix")] ProduitDTO produit)
{
if (ModelState.IsValid)
{
_ProduitService.Add(produit);
return RedirectToAction("Index");
}
return View(produit);
}
I want to use a html <select> to show client_id at the view !
Relation between classes : one client have many produit
i want to show ProduitID,Type,Description,Prix and client_id
public class ClientDTO
{
[Key]
[ScaffoldColumn(false)]
public int idClient { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Nom")]
public string nom { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Prénom")]
public string prenom { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Email")]
public string Email { get; set; }
public int Tel { get; set; }
}
public class ProduitDTO
{
[Key]
[ScaffoldColumn(false)]
public int ProduitID { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Type")]
public string Type { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Description")]
public string Description { get; set; }
[Required(ErrorMessage = "champ requis")]
[MinLength(3, ErrorMessage = "valeur trop courte")]
[DisplayName("Prix")]
public int Prix { get; set; }
public Nullable<int> client_id { get; set; }
public virtual ClientDTO client { get; set; }
}
You need to convert your ICollection<Produit> Produits to an IEnumerable<SelectListItem>. A great way to do this is by using a simple lambda:
IEnumerable<SelectListItem> dropdownItems = db.Client.Find(myClientId).Produits.Select(i => new SelectListItem{ Value = i.ProduitId.ToString(), Text = Produit.Description });
Attach it to your model somehow:
Model.DropDownItems = dropdownItems;
And then you can generate a dropdown-list in Razor using
#Html.DropDownListFor(Model.DropDownItems)
Voila.

Database Calculations - MVC 3 and CodeFirst

I'm trying to write a method that generates multiple commission slips. This is for a college, where clients are enrolled with tutors in a class called Enrollments. With this method, I am trying to accumulate the monthly fee of the tutors' clients multiplied by their commission percentages, as tutors earn a certain commission on the lessons they give. Here is my code for this:
public ActionResult CreateBulkCommissions()
{
var month = DateTime.Now.ToString("MMMM");
var enrolments = db.Enrollments.ToList();
var newCommissions = from enrolment in enrolments
select new TutorCommission()
{
CommissionAmount = enrolment.MonthlyFee,
CommissionMonth = month, // string constant
CommissionStatus = "Unpaid",
Tutor = enrolment.Tutor
};
foreach (var newCommission in newCommissions)
{
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
db.TutorCommission.Add(newCommission);
db.SaveChanges();
}
return RedirectToAction("Index");
}
The problem is that TutorCommission entries are created for each individual enrollment, instead of one entry per tutor (for the month) with the total commission amount. I.e. Ashley has 3 clients and therefore 3 enrollments and currently 3 TutorCommission entries are being created for him. I want to add up the enrollments amounts for one entry. In addition, the amount is not being multiplied by the commission percentage, so it is just saving as the full enrollment monthly fee. Relevant classes are:
public class Enrollment
{
[Key]
[Display(Name = "Enrollment ID Number")]
public long EnrollmentIDNumber { get; set; }
[Display(Name = "Client ID Number")]
public long ClientNumberID { get; set; }
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
[Display(Name = "Course Name")]
public string CourseName { get; set; }
[Display(Name = "Lesson Time")]
public string LessonTime { get; set; }
[Display(Name = "Lesson Day")]
public string LessonDay { get; set; }
[Display(Name = "Lesson Location")]
public string LessonLocation { get; set; }
[Display(Name = "Lesson Type")]
public string LessonType { get; set; }
[Display(Name = "Lesson Level")]
public string LessonLevel { get; set; }
[Display(Name = "Monthly Fee")]
public long MonthlyFee { get; set; }
public virtual Client Client { get; set; }
public virtual Tutor Tutor { get; set; }
}
public class TutorCommission
{
[Key]
[Display(Name = "Commission ID")]
public long CommissionID { get; set; }
[Display(Name = "Commission Month")]
public string CommissionMonth {get; set;}
[Display(Name = "Commission Amount")]
public double CommissionAmount { get; set; }
[Display(Name = "Commission Status")]
public string CommissionStatus { get; set; }
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
public virtual Tutor Tutor { get; set; }
public virtual ICollection<CommissionPayments> CommissionPayments { get; set; }
}
public class Tutor
{
[Key]
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
[Required]
[StringLength(50, ErrorMessage="First name must be less than 50 characters")]
[Display(Name = "First Name")]
public string TutorFirstName { get; set; }
[StringLength(50, ErrorMessage = "Last name must be less than 50 characters")]
[Display(Name = "Last Name")]
public string TutorLastName { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Birth Date")]
public DateTime? TutorBirthDate { get; set; }
[Display(Name = "Cellphone Number")]
public string TutorCellphoneNumber { get; set; }
[Display(Name = "Home Number")]
public string TutorHomeNumber { get; set; }
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email address")]
[Display(Name = "Email Address")]
public string TutorEmailAddress { get; set; }
[Display(Name = "Street Address")]
public string TutorStreetAddress { get; set; }
[Display(Name = "Suburb")]
public string TutorSuburb { get; set; }
[Display(Name = "City")]
public string TutorCity { get; set; }
[Display(Name = "Postal Code")]
public string TutorPostalCode { get; set; }
[Display(Name="Full Name")]
public string FullName
{
get
{
return TutorFirstName + " " + TutorLastName;
}
}
[Display(Name="Commission Percentage")]
[Required]
public double TutorCommissionPercentage { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<TutorCommission> TutorCommissions { get; set; }
}
Thanks,
Amy
You can try moving the grouping logic outside the foreach loop, then iterating on the grouped list. So instead of
foreach (var newCommission in newCommissions)
{
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
db.TutorCommission.Add(newCommission);
db.SaveChanges();
}
try
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
foreach (var tutorCom in TutorComs)
{
db.TutorCommission.Add(tutorCom);
db.SaveChanges();
}
See if that is closer to the desired result.

Categories