我在尝试从导航属性中获取数据时收到NullReferenceException
。
我正在尝试将 JSon 显示为导航属性' EventImage'中的数据。即使元素在属性内部并且所有内容都被引用,我也会得到null引用异常。我查询了数据库,得到了预期的结果,但是当我调用控制器的[get]动作方法时,只出现空引用异常。我猜即使没有合适的元素,并且由于一对一或一对一的关系,我应该实现' EventImage:null'作为JSon的结果。
域名模式:
public class EventDetail
{
[DatabaseGenerated(DatabaseGeneratedOption.None), Key, ForeignKey("Event")]
public int EventDetailId { get; set; }
[DisplayFormat(NullDisplayText = "No information")]
public string EventLocalization { get; set; }
[DataType(DataType.Date),
DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true,
NullDisplayText = "No information")]
public DateTime? EventDate { get; set; }
[DisplayFormat(NullDisplayText = "No information")]
public string EventDescription { get; set; }
public virtual EventImage EventImage { get; set; }
public virtual Event Event { get; set; }
public virtual ICollection<EventPrice> EventPrices { get; set; }
}
public class EventImage
{
[DatabaseGenerated(DatabaseGeneratedOption.None), Key, ForeignKey("EventDetail")]
public int EventImageId { get; set; }
public string EventImageBase64 { get; set; }
public virtual EventDetail EventDetail { get; set; }
}
逻辑模型:
public class SingleEventDetail
{
public int EventDetailId { get; set; }
public string EventLocalization { get; set; }
public DateTime? EventDate { get; set; }
public string EventDescription { get; set; }
public string EventImage { get; set; }
}
public class EventImage
{
public int EventImageId { get; set; }
public string EventImageBase64 { get; set; }
}
方法I调用内部控制器
public override SingleEventDetail GetById(int id)
{
var eventDetail = _eventDetailRepository.GetAll().Select(e => new SingleEventDetail
{
EventDetailId = e.EventDetailId,
EventDate = e.EventDate,
EventLocalization = e.EventLocalization,
EventDescription = e.EventDescription,
EventPrices =
_eventDetailRepository.GetById(id)
.EventPrices.Select(ep => new EventPriceForSingleEventDetail
{
Amount = ep.Amount,
Currency = ep.Currency,
IsFullPrice = ep.IsFullPrice
}).ToList(),
EventImage = e.EventImage.EventImageBase64
}).SingleOrDefault(e => e.EventDetailId == id);
return eventDetail;
}
_eventDetailRepository.GetAll()
public IEnumerable<EventDetail> GetAll()
{
return _context.EventDetail.ToList();
}
_eventDetailRepository.GetById(int id)
public EventDetail GetById(int id)
{
return _context.EventDetail.ToList().SingleOrDefault(c => c.EventDetailId == id);
}
答案 0 :(得分:0)
我找到了解决方案。延迟加载不适用于这个特定的'EventImage'导航属性,但我不知道为什么。 我已经将方法_eventDetailRepository.GetById(int id)更改为具有eager loagind的方法,现在一切正常。
public EventDetail GetById(int? id)
{
return _context.EventDetail.Include(e => e.EventPrices).Include(e => e.EventImage).SingleOrDefault(e => e.EventDetailId == id);
}