SelectList
is a generic object collection. It appears that you're populating a SelectList
with your object types and want to default the new likes
to the first one. In that case honestly just use the raw data.
var objectTypes = _db.ObjectTypes.ToList();
var defaultObjectType = objectTypes.FirstOrDefault();
likes.ObjectTypeId = defaultObjectType.Id ?? 0;
I don't know why you're creating a SelectList
here because it appears you're just updating your database which has nothing to do with the UI. So your code doesn't need this object. But for completeness if you had a SelectList
and needed to get back to the original object then you'd need to do a cast.
var selectedObjectType = selectList.SelectedValue as ObjectType;
likes.ObjectTypeId = selectedObjectType?.Id ?? 0;
Finally note that I hope you're not trying to retrieve the object type selected by the end user as part of your UI as the code you posted wouldn't work as you're creating a brand new select list in this code. To get what the user selected in your UI you need to use model binding like MVC normally uses.