#c# #entity-framework-core
#c# #entity-framework-core
Вопрос:
Система.InvalidCastException: ‘Столбец содержит нулевые данные’.
Кто-нибудь может мне помочь, пожалуйста? Я продолжаю получать столбец, содержащий исключение с нулевыми данными. Весь мой класс модели имеет строковый тип, почему я получаю эту ошибку?
Это исключение изначально было создано в этом стеке вызовов:
[External Code]
LXG.DataAccess.Repository.Repository<T>.GetALL(System.Linq.Expressions
.Expression<System.Func<T, bool>>, System.Func<System.Linq.IQueryable<T>,
System.Linq.IOrderedQueryable<T>>, string) in Repository.cs
LXG.Areas.Admin.Controllers.CMJobProgController.GetAll() in CMJobProgController.cs
[External Code]
PubCode.cs
namespace LXG.Models
{
[Table("PUBCODE", Schema = "LASIS")]
public class PubCode
{
[Required]
[MaxLength(3)]
[Display(Name = "Code Type")]
[Column("CODE_TYPE")]
public string CodeType { get; set; }
[Required]
[MaxLength(3)]
[Display(Name = "Code 1")]
[Column("CODE_1")]
public string Code1 { get; set; }
[Required]
[MaxLength(3)]
[Display(Name = "Code 2")]
[Column("CODE_2")]
public string Code2 { get; set; }
[Required]
[MaxLength(3)]
[Display(Name = "Code 3")]
[Column("CODE_3")]
public string Code3 { get; set; }
[Required]
[MaxLength(3)]
[Display(Name = "Code 4")]
[Column("CODE_4")]
public string Code4 { get; set; }
[Required]
[MaxLength(15)]
[Display(Name = "Code ACR")]
[Column("CODE_ACR")]
public string CodeACR { get; set; }
[Required]
[MaxLength(100)]
[Display(Name = "Code Description")]
[Column("CODE_DESC")]
public string CodeDesc { get; set; }
}
}
CMJobProgController.cs
public IActionResult GetAll()
{
//this one no problem
var allObj = _unitOfWork.cmJobProg.GetALL(j => j.JobNumber == "19950232");
//this one throws the exception
var pubcode = _unitOfWork.pubcode.GetALL(s => s.CodeType == "JPA");
return Json(new { data = allObj });
}
Repository.cs
public IEnumerable<T> GetALL(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includeProperties != null)
{
foreach (var includeProp in includeProperties.Split(",", StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
Комментарии:
1. Какой столбец? Я думаю, это может быть связано с
[Required]
атрибутом, который вы, похоже, имеете во всех столбцах.2. ДА. Я удаляю требование, тогда у него не будет ошибки.. Поскольку я извлекаю данные, предыдущие данные получили значение null. Большое спасибо Якобу Буску Соренсену. Я действительно новичок в .net core.
Ответ №1:
вы должны вернуться к ToList() или FirstOrDefault() . если ваше поле является временным ключом, который вы устанавливаете FirstOrDefault(), если не установлен временный ключ ToList() .
public IActionResult GetAll()
{
var allObj = _unitOfWork.cmJobProg.GetALL(j => j.JobNumber == "19950232").ToList(); //this part must chenge
var pubcode = _unitOfWork.pubcode.GetALL(s => s.CodeType == "JPA").ToList(); //this part must chenge
return Json(new { data = allObj });
}
или вы можете использовать другой способ получения данных из таблицы
pubcode, если CodeType не является первичным ключом
var pubcode = _unitOfWork.pubcode.Where(s => s.CodeType == "JPA").ToList();
если CodeType является первичным ключом
var pubcode = _unitOfWork.pubcode.Where(s => s.CodeType == "JPA").FirstOrDefault();