In an Action Result that does a HttpPost i get an error from EF
"ModelState.Errors Internal error in the expression evaluator"
My model in View is OrdineOmaggio
public partial class OrdineOmaggio
{
public int Id { get; set; }
public string Id_Gioielleria { get; set; }
public System.DateTime Data_Ordine { get; set; }
public virtual Consumatore MD_CONSUMATORE { get; set; }
public virtual Omaggio MD_OMAGGIO { get; set; }
public virtual CodiceRandomConsumatore MD_RANDOM_CONSUMATORE { get; set; }
}
My Action is so
public async Task<ActionResult> ChooseGift(
[Bind(Include ="Data_Ordine,MD_RANDOM_CONSUMATORE,MD_OMAGGIO,Id_Gioielleria")]
OrdineOmaggio ordineOmaggio,
string codiceOmaggio, string codice)
{
var randomConsumatore = _context.CodiciRandomConsumatori
.SingleOrDefault(c => c.Codice == codice) ??
new CodiceRandomConsumatore
{
Id = -1,
Codice = "",
Assegnato = null,
Distinzione = ""
};
var consumatore = _context.CodiciRandomConsumatori
.Where(c => c.Codice == codice)
.Select(c => c.MD_CONSUMATORE)
.SingleOrDefault();
var omaggio = _context.Omaggi
.SingleOrDefault(c => c.CodiceOmaggio == codiceOmaggio);
if (ModelState.IsValid)
{
ordineOmaggio.Data_Ordine = DateTime.Now;
ordineOmaggio.Id_Gioielleria = ordineOmaggio.Id_Gioielleria;
ordineOmaggio.MD_CONSUMATORE = consumatore; // FK
ordineOmaggio.MD_OMAGGIO = omaggio; // FK
ordineOmaggio.MD_RANDOM_CONSUMATORE = randomConsumatore; // FK
_context.OrdiniOmaggio.Add(ordineOmaggio);
randomConsumatore.Assegnato = true;
_context.SaveChanges();
return RedirectToAction("Success");
}
return View(ordineOmaggio);
}
The error is about dataAnnotation: it say that not all field all filled
The metadata is
public class OrdineOmaggioMetadata
{
[Required(ErrorMessage = "Scegli la gioiellereia.")]
public string Id_Gioielleria;
[Required(ErrorMessage = "Seleziona una foto.")]
public Omaggio MD_OMAGGIO;
...
}
In my view i placed
#Html.HiddenFor(m=> m.MD_OMAGGIO.CodiceOmaggio)
#Html.ValidationMessageFor(m => m.MD_OMAGGIO.CodiceOmaggio)
but this helper pass null to ActionResult
MD_OMAGGIO is a table foreign key for product codes.
what i wrong ?
Related
Its crashing on my CardDetailsView,the Details IActionResult in my CardsController
CardDetailsView-
public class CardDetailsViewModel
{
public string Id { get; set; }
public string Title { get; set; }
public string ImageUrl { get; set; }
public string Destination { get; set; }
public string Model { get; set; }
public string SNumber { get; set; }
public string QNumber { get; set; }
}
CardDetailsView-
#model CardDetailsViewModel
#{ ViewBag.Title = "Details"; }
Card Details
Title
Destination
Model
SNumber
QNumber
Details
CardsController-
public class CardsController : Controller
{
public readonly DigitalCardsDbContext data;
public CardsController(DigitalCardsDbContext data)
{
this.data = data;
}
public IActionResult Add() => View();
[HttpPost]
public IActionResult Add(CardAddViewModel card)
{
if(!ModelState.IsValid)
{
return View(card);
}
var cardd = new Card
{
Title = card.Title,
ImageUrl = card.ImageUrl,
Destination = card.Destination,
Receiver = card.Receiver,
Model = card.Model,
UserFullName = card.UserFullName,
SNumber = card.SNumber,
QNumber = card.QNumber,
PublicView = card.PublicView
};
this.data.Cards.Add(cardd);
this.data.SaveChanges();
return RedirectToAction("All","Cards");
}
public IActionResult All()
{
var cards = this.data.Cards
.Where(c => c.PublicView == true).ToList();
var usern = User.Identity.Name;
if(usern!=this.User.Identity.Name)
{
return BadRequest();
}
var cardsl = cards
.Select(c => new CardAllViewModel
{
Id = c.Id,
Title = c.Title,
ImageUrl = c.ImageUrl,
Destination = c.Destination,
SNumber = c.SNumber,
QNumber = c.QNumber
})
.ToList();
return View(cardsl);
}
public IActionResult Details(string cardId)
{
var card = this.data.Cards.Where(c => c.Id == cardId)
.Select(c => new CardDetailsViewModel
{
Id = c.Id,
ImageUrl = c.ImageUrl,
Title = c.Title,
Destination = c.Destination,
Model = c.Model,
SNumber = c.SNumber,
QNumber = c.QNumber
})
.SingleOrDefault();
return View(card);
}
The code is crashing on my View,on every div class,Title,ImageUrl,Etc.The exception is Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get returned null.
Here is snap-Error
Please verify the value in the image [url] it looks like that could be the reason.
could anyone tell me what am I doing wrong? I am getting null properties trying to bind.
Explaining:
My Controller Index looks ok, so that in my View I can see all the input values that I want to bind filled (IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario).
So far, everything looks good. But, after submit the page, in my Controller CheckOut all the properties in checkOut object binded is null, as you can see in the picture.
It was working fine, I dont know what I did so that it now is getting null properties.
I am using asp.net core 3.1 MVC
ViewModel
public class CheckOut
{
public Usuario Usuario { get; set; }
public UsuarioUnidade UsuarioUnidade { get; set; }
public CatalogoEndereco CatalogoEndereco { get; set; }
public UsuarioPagamento UsuarioPagamento { get; set; }
public byte IdPedidoAtendimento { get; set; }
public string PedidoAtendimentoNome { get; set; }
public decimal PedidoAtendimentoTaxa { get; set; }
public DateTime? HorarioAgendado { get; set; }
public byte IdPedidoTipoPagamento { get; set; }
public string PedidoTipoPagamento { get; set; }
public int IdUnidadeUsuario { get; set; }
public string Nome { get; set; }
public string NumEndereco { get; set; }
public string ComplementoEndereco { get; set; }
public string RuaNome { get; set; }
public string CidadeNome { get; set; }
public string EstadoNome { get; set; }
public string CEP { get; set; }
public byte? isCPF { get; set; }
public string CPF { get; set; }
public string NumeroCartao { get; set; }
public string CodCartao { get; set; }
}
Controller
public IActionResult Index()
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
Usuario usuario = new Usuario();
usuario = _context.Usuario
.SingleOrDefault(u => u.Email.Equals(user.Value) && u.IsAtivo == true);
CatalogoEndereco catalogoEndereco = new CatalogoEndereco();
catalogoEndereco = _context.CatalogoEndereco
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsAtivo == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioPagamento usuarioPagamento = new UsuarioPagamento();
usuarioPagamento = _context.UsuarioPagamento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioUnidade usuarioUnidade = new UsuarioUnidade();
usuarioUnidade = _context.UsuarioUnidade
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IdUnidadeNavigation.IsAtiva == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioAtendimento usuarioAtendimento = new UsuarioAtendimento();
usuarioAtendimento = _context.UsuarioAtendimento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
CheckOut checkOut = new CheckOut()
{
Usuario = usuario,
UsuarioUnidade = usuarioUnidade,
CatalogoEndereco = catalogoEndereco,
UsuarioPagamento = usuarioPagamento,
IdPedidoAtendimento = usuarioAtendimento.Tipo,
PedidoAtendimentoNome = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Nome,
PedidoAtendimentoTaxa = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Taxa
};
if (usuarioAtendimento.Tipo == 1)
{
checkOut.Nome = usuario.Nome;
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
}
if (catalogoEndereco != null)
{
checkOut.RuaNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = catalogoEndereco.NumEndereco;
checkOut.ComplementoEndereco = catalogoEndereco.Complemento;
checkOut.CEP = catalogoEndereco.IdEnderecoLogradouroNavigation.Cep;
}
}
else if (usuarioAtendimento.Tipo == 2)
{
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
checkOut.Nome = usuarioUnidade.IdUnidadeNavigation.Nome;
checkOut.RuaNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = usuarioUnidade.IdUnidadeNavigation.NumEndereco;
checkOut.CEP = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.Cep;
}
}
if (usuarioPagamento != null)
{
checkOut.IdPedidoTipoPagamento = usuarioPagamento.Tipo;
checkOut.PedidoTipoPagamento = _context.PedidoTipoPagamento
.FirstOrDefault(t => t.IdPedidoTipoPagamento == usuarioPagamento.Tipo).Nome;
checkOut.isCPF = 0;
checkOut.CPF = usuario.Cpf;
checkOut.NumeroCartao = null;
checkOut.CodCartao = null;
if (usuarioPagamento.Tipo == 1 || usuarioPagamento.Tipo == 2)
{
checkOut.NumeroCartao = "**** " + usuarioPagamento.Numero.Substring(12, 4);
checkOut.CodCartao = null;
}
}
return View(checkOut);
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CheckOut([Bind("IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario")] CheckOut checkOut)
{
if (ModelState.IsValid)
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
var cliente = _context.Usuario.SingleOrDefault(u => u.Email.Equals(user.Value));
var pedido = new Pedido()
{
IdUsuario = cliente.IdUsuario,
IdUnidade = checkOut.IdUnidadeUsuario,
IdPedidoCanalVenda = 1,
IdPedidoAtendimento = checkOut.IdPedidoAtendimento,
IdAtendente = null,
IdPedidoTipoPagamento = checkOut.IdPedidoTipoPagamento,
IdEntregador = null,
IdPedidoStatus = 1,
DataPedido = DateTime.Now,
DataEntrega = null,
HorarioAgendado = null,
TaxaServico = checkOut.PedidoAtendimentoTaxa
};
_context.Pedido.Add(pedido);
await _context.SaveChangesAsync()
.ConfigureAwait(false);
int lastPedido = pedido.IdPedido;
List<Carrinho> cart = JsonSerializeSessionHelper.Get<List<Carrinho>>(HttpContext.Session, "cart");
foreach (var item in cart)
{
var pedidoItens = new PedidoItens
{
IdPedido = lastPedido,
IdProduto = item.IdProduto,
IdProdutoTamanho = item.IdProdutoTamanho,
IdProdutoTipoMassa = item.IdProdutoTipoMassa,
IdProdutoMeia = item.IdProdutoMeia,
Quantidade = item.Quantidade,
Preco = item.Preco
};
_context.PedidoItens.Add(pedidoItens);
}
await _context.SaveChangesAsync()
.ConfigureAwait(false);
TempData["save"] = "Pedido realizado com sucesso";
HttpContext.Session.Remove("cart");
}
else
{
return RedirectToAction("Index", "Login");
}
return RedirectToAction("Index", "Pedido");
}
return View(checkOut);
}
View
#using (Html.BeginForm("CheckOut", "Carrinho", FormMethod.Post))
{
<button type="submit" class="btn btn-info btn-sm">
Pagar (R$ #(#ViewBag.SubTotal + Model.PedidoAtendimentoTaxa))
</button>
// I need these values for Bind!!
#*#Html.DisplayFor(m => m.IdPedidoAtendimento)
#Html.DisplayFor(m => m.PedidoAtendimentoTaxa)
#Html.DisplayFor(m => m.HorarioAgendado)
#Html.DisplayFor(m => m.IdPedidoTipoPagamento)
#Html.DisplayFor(m => m.IdUnidadeUsuario)*#
<input asp-for="IdPedidoAtendimento" value="#Model.IdPedidoAtendimento" id="txtIdPedidoAtendimento" name="txtIdPedidoAtendimento" hidden/>
<input asp-for="PedidoAtendimentoTaxa" value="#Model.PedidoAtendimentoTaxa" id="txtPedidoAtendimentoTaxa" name="txtPedidoAtendimentoTaxa" hidden/>
<input asp-for="HorarioAgendado" value="#Model.HorarioAgendado" id="txtHorarioAgendado" name="txtHorarioAgendado" hidden />
<input asp-for="IdPedidoTipoPagamento" value="#Model.IdPedidoTipoPagamento" id="txtIdPedidoTipoPagamento" name="txtIdPedidoTipoPagamento" hidden/>
<input asp-for="IdUnidadeUsuario" value="#Model.IdUnidadeUsuario" id="txtIdUnidadeUsuario" name="txtIdUnidadeUsuario" hidden/>
}
Model binding occurs based on the name attribute. You have the #Html.DisplayFor lines commented out, so it isn't binding there. For the <input> fields, you have manually entered a name of txt<PropertyName>, so it isn't binding on those, either.
ASP.NET will automatically create an appropriate name attribute just using the asp-for attribute to accommodate model binding.
I have a ViewModel and I would like to make a fonctionnal delete(GET) and deleteConfirmed(POST) so i can delete what ever data is stored in my DB
I don’t know and would like to know what step to take to complete the deleteConfirmed. There is normally auto-generated code but it’s not what I need.
here is my ViewModel
using System;
using ExploFormsDB.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ExploFormsDB.ViewModels
{
public class WorkShiftDetailViewModel
{
[Key]
public int WorkShiftId { get; set; }
public int? HoleId { get; set; }
public string HoleName { get; set; }
public int SurveyLocationId { get; set; }
public int SupplierId { get; set; }
public int ZoneId { get; set; }
public string SurveyLocation1 { get; set; }
public string SupplierName { get; set; }
public string ZoneName { get; set; }
public DateTime StartDay { get; set; }
public DateTime EndDay { get; set; }
public ICollection<WorkerViewModel> WorkShiftEmployees { get; set; }
}
}
Here is my Controller, i have included the Create to help have a better understanding. GET: Delete seems to be working correctly, i am having trouble with the Post. any help what so ever will do. if the question as been answered already please send me a link. I'm pretty new to c# and core and completly new to ViewModels
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(WorkShiftDetailViewModel workShiftDetailViewModel)
{
if (!ModelState.IsValid)
{
WorkShift ws = new WorkShift();
ws.StartDay = workShiftDetailViewModel.StartDay;
ws.EndDay = workShiftDetailViewModel.EndDay;
ws.SupplierId = workShiftDetailViewModel.SupplierId;
ws.SurveyLocationId = 1;
ws.ZoneId = workShiftDetailViewModel.ZoneId;
ws.HoleId = workShiftDetailViewModel.HoleId;
_context.Add(ws);
await _context.SaveChangesAsync();
foreach (WorkerViewModel member in workShiftDetailViewModel.WorkShiftEmployees)
{
if (member.isDeleted == false) {
WorkShiftTeam emp = new WorkShiftTeam();
emp.EmployeeId = member.EmployeeId;
emp.RoleId = member.RoleId;
emp.WorkShiftId = ws.WorkShiftId;
_context.Add(emp);
}
}
HttpContext.Session.SetInt32("wsId", ws.WorkShiftId);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(CreateSharedView));
}
return View(workShiftDetailViewModel);
}
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
List<WorkerViewModel> Workers = new List<WorkerViewModel>();
WorkShift ws = _context.WorkShift.Include(w => w.WorkShiftTeam).SingleOrDefault(x => x.WorkShiftId == id);
WorkShiftDetailViewModel detail = new WorkShiftDetailViewModel();
detail.HoleName = ws.HoleId == null ? "N/A" : _context.Hole.Find(ws.HoleId).HoleName;
detail.StartDay = ws.StartDay;
detail.EndDay = ws.EndDay;
detail.ZoneName = _context.Zone.Find(ws.ZoneId).ZoneName;
detail.SurveyLocation1 = _context.SurveyLocation.Find(ws.SurveyLocationId).SurveyLocation1;
detail.SupplierName = _context.Supplier.Find(ws.SupplierId).SupplierName;
detail.WorkShiftId = ws.WorkShiftId;
int order = 0;
var rolelist = new SelectList(_context.Role, "RoleId", "Role1");
var empsWithFullName = from e in _context.Employee.Where(a => a.IsActive)
select new
{
ID = e.EmployeeId,
FullName = e.LastName + ", " + e.FirstName
};
var empList = new SelectList(empsWithFullName, "ID", "FullName");
foreach (WorkShiftTeam member in ws.WorkShiftTeam.OrderBy(a => a.EmployeeId))
{
Workers.Add(new WorkerViewModel() { EmployeeId = member.EmployeeId, RoleId = member.RoleId, Index = order, Roles = rolelist, Employees = empList });
order++;
}
detail.WorkShiftEmployees = Workers;
return View(detail);
}
// POST: WorkShiftDetailViewModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
//??
} ```
Why you created an extra method for delete action as HttpGet? (that occurred conflict)
change it to:
[HttpGet]
public IActionResult GetById(int? id) { ... }
and just one delete method with this definition
[HttpPost]
public async Task<IActionResult> Delete(int? id) { ... }
I am having some trouble here. The situation is to update an existing record, at the same time, save a new row if there is no record by searching first the table.
When I am saving a new record, there is no problem. But when I'm trying to update an existing one, there are no changes. I tried to place some breakpoints specifically on the code that do the thing. It just ending up on the line if(!ModelState.IsValid).
Note:
Some of the lines are hard-coded for the sake of having some dummy data.
Function for retrieving some data from DB to pass to view model
[HttpGet]
public ActionResult CardNumberAssignment(string empId, int cardNumberId)
{
var getIdDetails = dbContext.CardNumberAssignments.Where(c => c.CardNumberId == cardNumberId && c.IsActive == true).SingleOrDefault();
if (cardNumberId == 0) //EMPLOYEE HAS NO CARD NUMBER YET
{
var viewModel = new CardNumberQRCodeVM
{
CardNumberId = 0,
CMId = empId,
OldQRCode = "No QR Code history",
OldReservedCardNumber = "No Card Number history",
NewReservedCardNumber = GetRandomCardNumber()
};
return View(viewModel);
}
else
{
if (getIdDetails.CMId != empId) //JUST CHECKING IF THE EMPLOYEE HAS THE CORRECT CARDNUMBERID FROM DB
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var empCardDetails = dbContext.CardNumberAssignments
.Include(c => c.ReservedCardNumber)
.Where(emp => emp.CMId == empId && emp.IsActive == true)
.Select(fields => new CardNumberQRCodeVM
{
CardNumberId = fields.CardNumberId,
CMId = empId,
OldQRCode = fields.QRCode,
IsActive = fields.IsActive,
OldReservedCardNumber = fields.ReservedCardNumber.CardNumber,
}).FirstOrDefault();
empCardDetails.NewReservedCardNumber = GetRandomCardNumber();
return View(empCardDetails);
}
}
Function for adding/editing record
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveIdInformation(CardNumberQRCodeVM vm)
{
if (!ModelState.IsValid)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// JUST ADDING/EDITING SOME CARD NUMBERS....
else
{
if (vm.CardNumberId == 0) //INSERT A NEW ROW FOR NEW CARD NUMBER AND QR CODE
{
var newCardNumber = new ReservedCardNumber
{
CardNumber = vm.NewReservedCardNumber,
IsActive = true,
CreatedDate = DateTime.Now,
CreatedBy = "Paolo",
ModifiedDate = DateTime.Now,
ModifiedBy = "Paolo"
};
dbContext.ReservedCardNumbers.Add(newCardNumber);
var newIdInfo = new CardNumberAssignment
{
CardNumberId = newCardNumber.Id,
QRCode = vm.NewQRCode,
CMId = vm.CMId,
IsActive = true,
CreatedDate = DateTime.Now,
CreatedBy = "Paolo",
ModifiedDate = DateTime.Now,
ModifiedBy = "Paolo"
};
dbContext.CardNumberAssignments.Add(newIdInfo);
}
else // EDIT EXISTING
{
var getEmployeeIdInDb = dbContext.CardNumberAssignments.Single(e => e.Id == vm.CardNumberId);
getEmployeeIdInDb.ReservedCardNumber.CardNumber = vm.NewReservedCardNumber;
getEmployeeIdInDb.QRCode = vm.NewQRCode;
getEmployeeIdInDb.IsActive = true;
getEmployeeIdInDb.ModifiedDate = DateTime.Now;
getEmployeeIdInDb.ModifiedBy = "Paolo";
}
dbContext.SaveChanges();
}
return RedirectToAction("CMDetails", "Admin", new { #empId = vm.CMId });
}
View model
public class CardNumberQRCodeVM
{
public int CardNumberId { get; set; }
public string CMId { get; set; }
[Display(Name = "Existing QR Code")]
public string OldQRCode { get; set; }
[Required]
[Display(Name = "New QR Code")]
public string NewQRCode { get; set; }
[Display(Name = "Resigned Cast Member?")]
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
public ReservedCardNumber ReservedCardNumber { get; set; }
[Display(Name = "Old Card Number")]
public string OldReservedCardNumber { get; set; }
[Display(Name = "New Card Number")]
public string NewReservedCardNumber { get; set; }
}
I'm calling this method by CascadingDropDownListFor and I'm getting an exception:
An exception of type 'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
public JsonResult GetRaca(string especieId)
{
int esp = Convert.ToInt32(especieId);
var rac = db.Raca.Where(c => c.EspecieId == esp).ToList();
var racas = new List<SelectListItem>();
foreach (var ra in rac)
{
var racaConteudo = db.RacaConteudo
.Where(c => c.RacaId == ra.RacaId)
.Where(c => c.IdiomaId == 1)
.First(); // <= The exception occurred here
racas.Add(new SelectListItem
{
Text = racaConteudo.RacaId.ToString(),
Value = racaConteudo.NomePopular
});
}
return Json(racas, JsonRequestBehavior.AllowGet);
}
The entity:
[Table("RacasConteudo")]
public class RacaConteudo
{
public RacaConteudo(long RacaId, string NomeCientifico, string NomePopular, long IdiomaId)
{
this.RacaId = RacaId;
this.NomeCientifico = NomeCientifico;
this.NomePopular = NomePopular;
this.IdiomaId = IdiomaId;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long RacaConteudoId { get; set; }
[ForeignKey("RacaId")]
public virtual Raca Raca { get; set; }
public long RacaId { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Nome Cientifico")]
public string NomeCientifico { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Nome Popular")]
public string NomePopular { get; set; }
[ForeignKey("IdiomaId")]
[Display(Name = "Idioma")]
public virtual Idioma Idioma { get; set; }
public long IdiomaId { get; set; }
}
Remove parameterized constructor public RacaConteudo(long RacaId, ..., long IdiomaId), and make the class partial.
[Table("RacasConteudo")]
public partial class RacaConteudo
^^^^^
{
/* public RacaConteudo(...) {} */
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long RacaConteudoId { get; set; }
....
}
Based on your updated question, Raca and RacaConteudo have relationship.
If so, you could even retrieve the desired result in single query which is a lot faster than querying multiple RacaConteudos for each and every Raca.
public JsonResult GetRaca(string especieId)
{
int esp = Convert.ToInt32(especieId);
var result = (from c in db.RacaConteudo
where c.Raca.EspecieId == esp && c.IdiomaId == 1
select new {Text = c.NomePopular, Value = c.RacaId.ToString()}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}