SelectList не отображается на .cshtml из-за ошибки конвертации
Есть объекты сущности:
[Table("friend")]
public partial class Friend
{
[Key]
[Column("Id_Friend")]
public long IdFriend { get; set; }
[Required(ErrorMessage = "Не указана фамилия")]
[DisplayName("Фамилия")]
[Column("Family_name", TypeName = "varchar(256)")]
public string FamilyName { get; set; }
[Required(ErrorMessage = "Не указано имя")]
[DisplayName("Имя")]
[Column("Name_", TypeName = "varchar(256)")]
public string Name { get; set; }
[DisplayName("Отчество")]
[Column("Patronymic_name", TypeName = "varchar(256)")]
public string PatronymicName { get; set; }
[DisplayName("Дата рожд.")]
[Required(ErrorMessage = "Не указана дата рождения")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Column("Date_birth", TypeName = "date")]
public DateTime? DateBirth { get; set; }
[Required(ErrorMessage = "Не указан насел. п-т")]
[DisplayName("Насел. пункт")]
[Column("City_id")]
public int? CityId { get; set; }
[DisplayName("Округ")]
[Column("District_id")]
public int? DistrictId { get; set; }
[Required(ErrorMessage = "Не указана улица")]
[DisplayName("Улица")]
[Column("Street_id")]
public int? StreetId { get; set; }
[DisplayName("Микрорайон")]
[Column("MicroDistrict_id")]
public int? MicroDistrictId { get; set; }
[Required(ErrorMessage = "Не указан дом")]
[DisplayName("Дом")]
[Column("House_id")]
public int? HouseId { get; set; }
[DisplayName("Строение")]
[Column(TypeName = "varchar(10)")]
public string Building { get; set; }
[DisplayName("Квартира")]
[Column(TypeName = "varchar(10)")]
public string Apartment { get; set; }
[MinLength(11)]
[MaxLength(12)]
[RegularExpression(@"[+]?[0-9]+"), StringLength(12)]
[DisplayName("Тел. избирателя")]
[Column(TypeName = "varchar(12)")]
public string Telephone { get; set; }
[DisplayName("Организация")]
[Column(TypeName = "varchar(256)")]
public string Organization { get; set; }
[DisplayName("Сфера деят-ти")]
[Column("FieldActivity_id")]
public int? FieldActivityId { get; set; }
[MinLength(11)]
[MaxLength(12)]
[RegularExpression(@"[+]?[0-9]+"), StringLength(12)]
[DisplayName("Тел. ответств-го")]
[Column("Phone_number_responsible", TypeName = "varchar(12)")]
public string PhoneNumberResponsible { get; set; }
[DisplayName("Адресс")]
[Column(TypeName = "varchar(500)")]
public string Adress { get; set; }
[DisplayName("QRcode")]
[Column("QRcode", TypeName = "varchar(4500)")]
public string Qrcode { get; set; }
[DisplayName("Примечание")]
[Column(TypeName = "varchar(256)")]
public string Description { get; set; }
[DisplayName("Агитатор")]
[Column("User_id")]
public long? UserId { get; set; }
[DisplayName("Группа")]
[Column("GroupU_id")]
public int? GroupUId { get; set; }
[DisplayName("Населен. п-т")]
[ForeignKey(nameof(CityId))]
[InverseProperty("Friends")]
public virtual City City { get; set; }
[DisplayName("Округ")]
[ForeignKey(nameof(DistrictId))]
[InverseProperty("Friends")]
public virtual District District { get; set; }
[DisplayName("Сфера деят-ти")]
[ForeignKey(nameof(FieldActivityId))]
[InverseProperty(nameof(Fieldactivity.Friends))]
public virtual Fieldactivity FieldActivity { get; set; }
[DisplayName("Группа")]
[ForeignKey(nameof(GroupUId))]
[InverseProperty(nameof(Groupu.Friends))]
public virtual Groupu GroupU { get; set; }
[DisplayName("Дом")]
[ForeignKey(nameof(HouseId))]
[InverseProperty("Friends")]
public virtual House House { get; set; }
[DisplayName("Микрорайон")]
[ForeignKey(nameof(MicroDistrictId))]
[InverseProperty(nameof(Microdistrict.Friends))]
public virtual Microdistrict MicroDistrict { get; set; }
[DisplayName("Улица")]
[ForeignKey(nameof(StreetId))]
[InverseProperty("Friends")]
public virtual Street Street { get; set; }
[ForeignKey(nameof(UserId))]
[InverseProperty("Friends")]
public virtual User User { get; set; }
}
[Table("user")]
public partial class User
{
public User()
{
Friends = new HashSet<Friend>();
Groupsusers = new HashSet<Groupsusers>();
}
[Key]
[Column("Id_User")]
public long IdUser { get; set; }
[DisplayName("Пользователь")]
[Required(ErrorMessage = "Не указано имя")]
[Column(TypeName = "varchar(100)")]
public string UserName { get; set; }
[Required(ErrorMessage = "Не указан пароль")]
[Column(TypeName = "varchar(100)")]
public string Password { get; set; }
[DisplayName("Роль")]
[Column("Role_id")]
public int? RoleId { get; set; }
[DisplayName("Фамилия")]
[Required(ErrorMessage = "Не указана фамилия")]
[Column("Family_name", TypeName = "varchar(256)")]
public string FamilyName { get; set; }
[DisplayName("Имя")]
[Required(ErrorMessage = "Не указано имя")]
[Column("Name_", TypeName = "varchar(256)")]
public string Name { get; set; }
[DisplayName("Отчество")]
[Column("Patronymic_name", TypeName = "varchar(256)")]
public string PatronymicName { get; set; }
[DisplayName("Дата рождения")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Column("Date_birth", TypeName = "date")]
public DateTime? DateBirth { get; set; }
[MinLength(11)]
[MaxLength(12)]
[RegularExpression(@"[+]?[0-9]+"), StringLength(12)]
[DisplayName("Телефон")]
[Column(TypeName = "varchar(12)")]
public string Telephone { get; set; }
[DisplayName("Роль")]
[ForeignKey(nameof(RoleId))]
[InverseProperty("Users")]
public virtual Role Role { get; set; }
[DisplayName("Друзья")]
[InverseProperty("User")]
public virtual ICollection<Friend> Friends { get; set; }
[DisplayName("Группы")]
[InverseProperty("User")]
public virtual ICollection<Groupsusers> Groupsusers { get; set; }
[DisplayName("Кол-во избирателей")]
[NotMapped]
public string numberFriends { get; set; }
}
На странице на которой происходит правка объекта, есть следующее поле для отображения списка объектов User:
...
<div class="form-group">
<select asp-for="UserId" class="form-control" asp-items="ViewBag.UserId"></select>
</div>
...
И в этой строке при вызове данной страницы выдает ошибку:
Unable to cast object of type 'System.DBNull' to type 'System.String'
Контроллер возвращающий контент для представления:
Authorize(Roles = "admin, user")]
public class FriendsController : Controller
{
private readonly ILogger<FriendsController> _logger;
private readonly VoterCollectorContext _context;
public FriendsController(VoterCollectorContext context, ILogger<FriendsController> logger)
{
_logger = logger;
_context = context;
}
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var friend = await _context.Friend.FindAsync(id);
if (friend == null)
{
return NotFound();
}
ViewData["CityId"] = new SelectList(_context.City, "IdCity", "Name", friend.CityId);
ViewData["DistrictId"] = new SelectList(_context.District, "IdDistrict", "Name", friend.DistrictId);
ViewData["FieldActivityId"] = new SelectList(_context.Fieldactivity, "IdFieldActivity", "Name", friend.FieldActivityId);
ViewData["GroupUId"] = new SelectList(_context.Groupu, "IdGroup", "Name", friend.GroupUId);
ViewData["HouseId"] = new SelectList(_context.House, "IdHouse", "Name", friend.HouseId);
ViewData["MicroDistrictId"] = new SelectList(_context.Microdistrict, "IdMicroDistrict", "Name", friend.MicroDistrictId);
ViewData["PollingStationId"] = new SelectList(_context.PollingStation, "IdPollingStation", "Name", friend.PollingStationId);
var selectLists= new SelectList(_context.Street, "IdStreet", "Name", friend.StreetId);
ViewData["StreetId"] = new SelectList(_context.Street, "IdStreet", "Name", friend.StreetId);
var selectListUsers = new SelectList(_context.User, "IdUser", "FamilyName", friend.UserId);
ViewData["UserId"] = selectListUsers;
return View(friend);
}
}
Если посмотреть через отладчик, что возвращает контроллер для этого списка, то он не пустой

Подробное описание ошибки:
MySqlConnector.Core.Row.GetString(int ordinal) in Row.cs MySql.Data.MySqlClient.MySqlDataReader.GetString(int ordinal) in MySqlDataReader.cs lambda_method(Closure , QueryContext , DbDataReader , ResultContext , int[] , ResultCoordinator ) Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+Enumerator.MoveNext() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItems() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator() System.Collections.Generic.List..ctor(IEnumerable collection) System.Linq.Enumerable.ToList(IEnumerable source) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(string optionLabel, IEnumerable selectList, ICollection currentValues) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateSelect(ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable selectList, ICollection currentValues, bool allowMultiple, object htmlAttributes) Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext) AspNetCore.Views_Friends_Edit.b__23_0() in Edit.cshtml + Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder) Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count) AspNetCore.Views_Friends_Edit.ExecuteAsync() in Edit.cshtml + ViewData["Title"] = "Edit"; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'. at MySqlConnector.Core.Row.GetString(Int32 ordinal) in //src/MySqlConnector/Core/Row.cs:line 377 at MySql.Data.MySqlClient.MySqlDataReader.GetString(Int32 ordinal) in //src/MySqlConnector/MySql.Data.MySqlClient/MySqlDataReader.cs:line 272 at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator ) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable
1.Enumerator.MoveNext() at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField() at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItems() at Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(String optionLabel, IEnumerable1 selectList, ICollection1 currentValues)
at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateSelect(ViewContext viewContext, ModelExplorer modelExplorer, String optionLabel, String expression, IEnumerable1 selectList, ICollection1 currentValues, Boolean allowMultiple, Object htmlAttributes) at Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext context, TagHelperOutput output) at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext) at AspNetCore.Views_Friends_Edit.b__23_0() in D:\My_PROGRAMS\voteCollector\Views\Friends\Edit.cshtml:line 123 at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(Boolean useCachedResult, HtmlEncoder encoder) at Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count) at AspNetCore.Views_Friends_Edit.ExecuteAsync() in D:\My_PROGRAMS\voteCollector\Views\Friends\Edit.cshtml:line 4 at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts) at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable1 statusCode) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable1 statusCode) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)