ASP.NET MVC、LINQ 和 UpdateModel 问题

发布于 2024-07-26 11:04:56 字数 3072 浏览 3 评论 0原文

好的 - 我在数据库中有两个表:员工和公司。 以下是每个公司的基本模式

Table Companies
CompanyID - GUID - PK
CompanyName - NVarChar(100)
Other Descriptive Fields....

Table Employees
EmployeeID - GUID - PK
CompanyID - GUID - FK
Employee Descriptive Fields...

所以现在我有一对多的关系,因为每个公司可以有多名员工。 我还为我的员工类创建了一个具有以下功能的数据存储库:

    Public Function GetEmployee(ByVal company As String, ByVal id As Guid) As DB.EmpWithComp.employee
    Dim emp As DB.EmpWithComp.employee = (From e In db.employees Where e.employeeID = id And e.company.companyName= company Select e).Single
    Return emp
End Function

    Public Sub save()
    db.SubmitChanges()
End Sub

到目前为止,一切都运行良好。 当我需要编辑员工时,问题就出现了。 这是我的控制器功能

    <AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal id As Guid, ByVal company As String, ByVal formValues As FormCollection) As ActionResult
    Dim e As New DB.EmpWithComp.employee
    e = db.GetEmployee(company, id)
    Try
        UpdateModel(e)
        db.save()
        Return RedirectToAction("Index")
    Catch ex As Exception
        Return View(e)
    End Try
End Function

Function Edit(ByVal id As Guid, ByVal company As String) As ActionResult
    Dim e As New DB.EmpWithComp.employee
    e = db.GetEmployee(company, id)
    If Not e Is Nothing Then
        Return View(e)
    Else
        Return View("~/Views/Admin/Employees/NotFound.aspx")
    End If
End Function

找到了员工,填充了编辑表单,并且按预期触发了发布功能。 然而,我的 updateModel 失败了,没有真正的解释。 我跟踪了 updateModel 的代码,所有属性都被分配了正确的值。 但是,当 updateModel 到达 LinqToSql 类中的以下部分时,company 的值为 Nothing,这就是导致失败的原因

<Association(Name:="company_employee", Storage:="_company", ThisKey:="companyID", IsForeignKey:=true)>  _
    Public Property company() As company
        Get
            Return Me._company.Entity
        End Get
        Set
            Dim previousValue As company = Me._company.Entity
            **If ((Object.Equals(previousValue, value) = false)  _
                        OrElse**  (Me._company.HasLoadedOrAssignedValue = false)) Then
                Me.SendPropertyChanging
                If ((previousValue Is Nothing)  _
                            = false) Then
                    Me._company.Entity = Nothing
                    previousValue.employees.Remove(Me)
                End If
                Me._company.Entity = value
                If ((value Is Nothing)  _
                            = false) Then
                    value.employees.Add(Me)
                    Me._companyID = value.companyID
                Else
                    **Me._companyID = CType(Nothing, System.Guid)**
                End If
                Me.SendPropertyChanged("company")
            End If
        End Set
    End Property

我在 FK 关系中缺少什么? 公司的先前值设置为进入 UpdateModel 的正确值,但未设置当前值。 如果我手动设置每个属性(e.firstname = request("firstname") 等)并在 dataRepository 上调用我的保存方法或删除关系并使用 UpdateModel,则一切正常。 我宁愿使用 UpdateModel,因为它使代码更清晰,等等。很抱歉这篇冗长的文章,但这让我发疯。 有任何想法吗?

顺便说一句,我并不是想更改 FK,只是简单地更新员工姓名。

Ok - I have two tables in the database, employees and companies. Here are the basic schemas for each

Table Companies
CompanyID - GUID - PK
CompanyName - NVarChar(100)
Other Descriptive Fields....

Table Employees
EmployeeID - GUID - PK
CompanyID - GUID - FK
Employee Descriptive Fields...

So now I have a one to many relationship as each company can have multiple employees. I have also created a dataRepository for my employee class with the following functions:

    Public Function GetEmployee(ByVal company As String, ByVal id As Guid) As DB.EmpWithComp.employee
    Dim emp As DB.EmpWithComp.employee = (From e In db.employees Where e.employeeID = id And e.company.companyName= company Select e).Single
    Return emp
End Function

    Public Sub save()
    db.SubmitChanges()
End Sub

Everything so far is working great. The issue comes when I need to edit an employee. Here are my controller functions

    <AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal id As Guid, ByVal company As String, ByVal formValues As FormCollection) As ActionResult
    Dim e As New DB.EmpWithComp.employee
    e = db.GetEmployee(company, id)
    Try
        UpdateModel(e)
        db.save()
        Return RedirectToAction("Index")
    Catch ex As Exception
        Return View(e)
    End Try
End Function

Function Edit(ByVal id As Guid, ByVal company As String) As ActionResult
    Dim e As New DB.EmpWithComp.employee
    e = db.GetEmployee(company, id)
    If Not e Is Nothing Then
        Return View(e)
    Else
        Return View("~/Views/Admin/Employees/NotFound.aspx")
    End If
End Function

The employee is found, the edit form is populated and the post function is firing as it should. However, my updateModel fails with no real explanation. I traced the code going through the updateModel and all attributes are being assigned the correct values. However, when the updateModel gets to the following section in the LinqToSql class, the value for company is Nothing and this is what is causing the failure

<Association(Name:="company_employee", Storage:="_company", ThisKey:="companyID", IsForeignKey:=true)>  _
    Public Property company() As company
        Get
            Return Me._company.Entity
        End Get
        Set
            Dim previousValue As company = Me._company.Entity
            **If ((Object.Equals(previousValue, value) = false)  _
                        OrElse**  (Me._company.HasLoadedOrAssignedValue = false)) Then
                Me.SendPropertyChanging
                If ((previousValue Is Nothing)  _
                            = false) Then
                    Me._company.Entity = Nothing
                    previousValue.employees.Remove(Me)
                End If
                Me._company.Entity = value
                If ((value Is Nothing)  _
                            = false) Then
                    value.employees.Add(Me)
                    Me._companyID = value.companyID
                Else
                    **Me._companyID = CType(Nothing, System.Guid)**
                End If
                Me.SendPropertyChanged("company")
            End If
        End Set
    End Property

What am I missing with the FK relationship? The previous value for company is set to the correct value going into the UpdateModel, but the current value is not set. If I manually set each property (e.firstname = request("firstname"), etc) and call my save method on the dataRepository or remove the relationship and use UpdateModel, everything works properly. I would rather use the UpdateModel as it makes the code cleaner, etc. Sorry for the lengthy post, but this is driving me nuts. Any ideas?

BTW, I am not trying to change the FK, just simply update the employee name.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2024-08-02 11:04:57

你的看法如何?

像这样?

如果是,UpdateModel 会尝试将 request("Company") 中的字符串写入 e.Company,它不是字符串,而是一个对象。

您真正想要更改的是 Employee.CompanyID 对吗? 您可以通过使用具有新 ID 的隐藏输入来完成此操作,或者如果您想通过 CompanyName 查找 CompanyID,您可以编写自己的 ModelBinder。


编辑

哦,你不想更新公司,对不起我的错。
在这种情况下,您需要告诉 UpdateModel 忽略您的 POST 中存在的公司,

Function Edit(ByVal id As Guid, ByVal company As String... 

您可以通过将公司设置为排除属性来实现此目的,如下所示

Dim exclude() As String = {"company"}
UpdateModel(e, String.Empty, Nothing, exclude)

或我喜欢的,您可以开始为您的字段使用前缀,如下所示,

<%=Html.Textbox("Employee.Firstname", ViewData.Model.Firstname)>%

并像这样调用 UpdateModel

UpdateModel(e, "Employee")

how does your view look like?

like this?

if yes, UpdateModel would try to write the string in request("Company") to e.Company which isn`t a string but an object.

what you really want to change is the Employee.CompanyID right? you can do this by using a Hidden Input with the new ID or if you want to find the CompanyID by the CompanyName you could write your own ModelBinder.


EDIT

oh you dont event want to update the company, sry my fault.
in that case you need to tell UpdateModel to ignore the company which is present in your POST

Function Edit(ByVal id As Guid, ByVal company As String... 

you can do this by setting company as excluded property like this

Dim exclude() As String = {"company"}
UpdateModel(e, String.Empty, Nothing, exclude)

or what i prefer, you could start using prefixs for your fields like this

<%=Html.Textbox("Employee.Firstname", ViewData.Model.Firstname)>%

and call UpdateModel like this

UpdateModel(e, "Employee")

hth

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文