none
'Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.' RRS feed

  • Question

  • I am new to MVC and I am trying to create an edit form that allows me to edit data in an entity and it's child entity at the same time.

    Below are my two Models

    Public Class tblInspection
        <StringLength(6)>
        Public Property Inspection_Mooring_Code As String
        '<DataType(DataType.DateTime)>
        <DisplayFormat(DataFormatString:="{0:dd-MM-yyyy}", ApplyFormatInEditMode:=True)>
        Public Property Inspection_Date As DateTime?
        <DisplayFormat(NullDisplayText:="")>
        Public Property Inspection_Passed As Boolean?
        <StringLength(5000)>
        Public Property Inspection_Comments As String
        <Key>
        Public Property Inspection_ID As Integer
        <StringLength(2)>
        Public Property Inspection_Mooring_zone As String
        <DisplayFormat(NullDisplayText:="")>
        Public Property Inspection_Mooring_Cycle As System.Int32?
        <StringLength(2)>
        Public Property InspectionMooringInspectorCode As String
        <StringLength(50)>
        Public Property InspectionContractor As String
        <StringLength(255)>
        Public Property InspectionClient As String
        <StringLength(255)>
        Public Property InspectionAddress As String
        <StringLength(100)>
        Public Property Inspectionemail As String
        <DisplayFormat(NullDisplayText:="")>
        Public Property InspectionConsentForm As System.Int16
        <StringLength(150)>
        Public Property InspectionLicencedHolder As String
        <StringLength(100)>
        Public Property InspectionPhone As String
        <StringLength(100)>
        Public Property InspectionMobile As String
        <StringLength(20)>
        Public Property InspectionInspectionRegime As String
        <StringLength(4)>
        Public Property InspectionMooring_Area As String
        <StringLength(20)>
        Public Property InspectionBuoy_Colour As String
        <StringLength(50)>
        Public Property InspectionVessel_Name As String
        <DisplayFormat(NullDisplayText:="")>
        Public Property InspectionVessel_Length As Double?
        <StringLength(5)>
        Public Property InspectionWeight_Tag As String
        <StringLength(7)>
        Public Property InspectionLatitude As String
        <StringLength(8)>
        Public Property InspectionLongitude As String
        <StringLength(6)>
        Public Property InspectionNotes As String
        Public Property InspectionMooring_Condition_Summary As String
        <DisplayFormat(NullDisplayText:="")>
        Public Property InspectionDateEntered As Date?
        <StringLength(20)>
        Public Property InspectionStatus As String

        Public Property MooringInspectionDetails() As List(Of MooringInspectionDetail)

    End Class

    Public Class MooringInspectionDetail
        <Key>
        Public Property MooringInspectionDetailID As Integer
        <ForeignKey("ParentInspection")>
        Public Property Inspection_ID As Integer
        <StringLength(50)>
        Public Property MooringInspectionDetailItem As String
        <StringLength(50)>
        Public Property MooringInspectionDetailSize As String
        <StringLength(50)>
        Public Property MooringInspectionDetailLength As String
        <StringLength(10)>
        Public Property MooringInspectionDetailResult As String
        <StringLength(10)>
        Public Property MooringInspectionDetailNew As String
        Public Property ParentInspection() As tblInspection
    End Class

    And here is my Edit action in my tblinspectionController

    Function Edit(ByVal id As Integer?) As ActionResult
                If IsNothing(id) Then
                    Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
                End If
                Dim tblInspection As tblInspection = db.tblInspections.Include(Function(i) i.MooringInspectionDetails).Where(Function(c) id.Equals(c.Inspection_ID)).Single
                If IsNothing(tblInspection) Then
                    Return HttpNotFound()
                End If

                Return View(tblInspection)
            End Function

    But when the code runs and it gets to the include statement it fails with the above error.

    What have I done wrong

    Thanks in advance

    Frosty

    Friday, November 22, 2019 12:42 AM

All replies

  • Hello,

    Don't use Equals, use =

    Dim tblInspection As tblInspection = db.tblInspections.Include(Function(i) i.MooringInspectionDetails).Single(Function(c) id = c.Inspection_ID)


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, November 22, 2019 2:43 AM
    Moderator
  • Where(Function(c) id.Equals(c.Inspection_ID)).

    The above statement is causing .NET to use the base object in .NET and  its  Equals function,  and EF doesn't view a base object function  as a primitive type in this situation or as an EDM primitive type.

    https://docs.microsoft.com/en-us/dotnet/api/system.object?view=netframework-4.8

    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/entity-data-model-primitive-data-types

    Where(Function(c) id = c.Inspection_ID).

    It is what it should be as explained by Karen, becuase id type is a primitive type integer on the ActionMethod signature and the EDM Inspection_ID is being looked at as a EDM primitive type.

    A couple of other things since you're new to ASP.NET MVC.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    This applies to VB.NET usage too of the MVC UI design pattern

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    <end>

    ASP.NET MVC issues using VB.NET can be discussed at the ASP.NET forums.

    http://forums.asp.net/

    An example of thin controller principles using SoC in MVC.

    Imports System.Web.Mvc
    Imports ProgMgmntVB.Models
    
    Namespace Controllers
        Public Class ProjectController
            Inherits BaseController
    
            private readonly _projectModel As IProjectModel 
            private readonly _modelHelper As IModelHelper 
    
            public sub New (projectModel As IProjectModel, modelHelper As IModelHelper)
                _projectModel = projectModel
                _modelHelper = modelHelper
            End sub
    
            ' GET: Project
            <Authorize>
            public Function Index() As ActionResult
                Return View(_projectModel.GetProjectsByUserId(User.Identity.Name))
            End Function
    
            <Authorize>
            public Function  Details(Optional id As Int32 = 0) As ActionResult
                return  IIf(id = 0, nothing, View(_projectModel.Edit(id)))
            End Function
           
            <Authorize>
            public Function  Edit(Optional id As Int32 = 0) As ActionResult 
                return  IIf(id = 0, nothing, View(_projectModel.Edit(id)))
            End Function
    
            <Authorize>
            public Function  Create() as ActionResult
                return View(_projectModel.Create())
            End Function
            
            <Authorize>
            <HttpPost>
            public  Function Create(project as ProjectViewModels.Project, submit As string ) As ActionResult
    
                if submit = "Cancel" Then
                    return RedirectToAction("Index")
                End If
    
                Call ValidateddlProjectTypes()
    
                project.ProjectType = Request.Form("ddlProjectTypes")
    
                If ModelState.IsValid And _modelHelper.IsEndDateLessThanStartDate(project, "Project") Then
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.")
                End If
    
                if Not ModelState.IsValid Then
                    return View(_projectModel.PopulateSelectedList(project))
                End If
    
                _projectModel.Create(project, User.Identity.Name)
                return RedirectToAction("Index")
    
            End Function
         
            <Authorize>
            <HttpPost>
            public Function  Edit(project as ProjectViewModels.Project, submit As string ) As ActionResult
    
                if submit = "Cancel" Then
                    return RedirectToAction("Index")
                End If
    
                If ModelState.IsValid And _modelHelper.IsEndDateLessThanStartDate(project, "Project") Then
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.")
                End If
    
                if Not ModelState.IsValid Then
                    return View(_projectModel.PopulateSelectedList(project))
                End If
    
                dim theproject = project
    
                theproject.ProjectType = Request.Form("ProjectType")
    
                _projectModel.Edit(theproject, User.Identity.Name)
    
                return RedirectToAction("Index")
    
            End Function
    
            public  Function Delete(Optional id As Int32 = 0) as ActionResult
    
                if id > 0 Then
                   _projectModel.Delete(id)
                end If
    
                return RedirectToAction("Index")
    
            End Function
            
            public Function  Cancel() As ActionResult
                return RedirectToAction("Index", "Home")
            End Function
            
            public function UploadFile(id As Int32) As ActionResult
                return RedirectToAction("UploadFile", "Upload", new With { .id = id, .type = "PM" })
            End function
           
            private sub ValidateddlProjectTypes()
    
                if Request.Form("ddlProjectTypes") = String.Empty Then
                    exit sub
                End If
    
                for each  key1 in ModelState.Keys.ToList().Where(Function(key) ModelState.ContainsKey(key))
    
                    if key1 <> "ProjectType" Then
                        continue for
                    End If
    
                    ModelState(key1).Errors.Clear()
                next
    
            End sub
        End Class
    End Namespace


    • Edited by DA924x Friday, November 22, 2019 4:55 AM
    Friday, November 22, 2019 4:51 AM