I\'ve narrowed this down to some issue between Code First and Database first EF, but I\'m not sure how to fix it. I\'ll try to be as clear as I can, but I honestly am missin
I also had this problem and it seems like there are a few different causes. For me it was having an id property mistakenly defined as int instead of long in the parent class that contained a navigation object. The id field in the database was defined as bigint which corresponds to long in C#. This didn't cause a compile time error but did cause the same run time error as the OP got:
// Domain model parent object
public class WidgetConfig
{
public WidgetConfig(long id, int stateId, long? widgetId)
{
Id = id;
StateId = stateId;
WidgetId = widgetId;
}
private WidgetConfig()
{
}
public long Id { get; set; }
public int StateId { get; set; }
// Ensure this type is correct
public long? WidgetId { get; set; }
public virtual Widget Widget { get; set; }
}
// Domain model object
public class Widget
{
public Widget(long id, string name, string description)
{
Id = id;
Name = name;
Description = description;
}
private Widget()
{
}
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
// EF mapping
public class WidgetConfigMap : EntityTypeConfiguration
{
public WidgetConfigMap()
{
HasKey(x => x.Id);
ToTable(nameof(WidgetConfig));
Property(x => x.Id).HasColumnName(nameof(WidgetConfig.Id)).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(x => x.StateId).HasColumnName(nameof(WidgetConfig.StateId));
Property(x => x.WidgetId).HasColumnName(nameof(WidgetConfig.WidgetId));
}
}
// Service
public class WidgetsService : ServiceBase, IWidgetsService
{
private IWidgetsRepository _repository;
public WidgetsService(IWidgetsRepository repository)
{
_repository = repository;
}
public List ListWithDetails()
{
var list = _repository.ListWithDetails();
return new WidgetConfigMapping().ConvertModelListToDtoList(list).ToList();
}
}
// Repository
public class WidgetsRepository: BaseRepository, IWidgetsRepository
{
public WidgetsRepository(Context context)
: base(context, id => widget => widget.Id == id)
{
}
public IEnumerable ListWithDetails()
{
var widgets = Query
.Include(x => x.State)
.Include(x => x.Widget);
return widgets;
}
}