none
Problem updating related Property RRS feed

  • Question

  • Hello there! Here's my problem:

    I've this simple Update view:

    @Imports LibIndicadoresBMG.Entidades
    @ModelType LibIndicadoresBMG.Entidades.Usuario
    @Code
    	ViewBag.TituloPagina = "Editar Usuário"
    	Dim db As New ContextoIndicadoresBMG()
    End Code
    
    <div class="grid grid_24">
    	<form class="form" method="post">
    		<div class="field input">
    		<label>Email:</label>
    		<div class="fields">	
    			@Html.EditorFor(Function(model) model.Email, New With {.size = 50, .name = "field"})
    		</div>			
    		@Html.ValidationMessageFor(Function(model) model.Email)
    		</div>
    
    	   <div class="field input">
    		<label>Senha:</label>
    		<div class="fields">	
    			@Html.EditorFor(Function(model) model.Senha, New With {.size = 50, .name = "field"})
    		</div>			
    		@Html.ValidationMessageFor(Function(model) model.Senha)
    		</div>
    
    		<div class="field input">
    		<label>Empresa:</label>
    		<div class="fields">	
    			@Html.EditorFor(Function(model) model.Empresa, New With {.size = 50, .name = "field"})
    		</div>			
    		@Html.ValidationMessageFor(Function(model) model.Empresa)
    		</div>
    
    		<div class="field input">
    		<label>Fornecedor:</label>
    		<div class="fields">	
    			@Html.DropDownListFor(Function(model) model.Fornecedor.Id, New SelectList(db.Fornecedores.OrderBy(Function(b) b.Nome).ToList(), "Id", "Nome"))
    		</div>			
    		</div>
    
    		<div class="field input">
    		<label>Admin?:</label>
    		<div class="fields">	
    			@Html.EditorFor(Function(model) model.Admin)
    		</div>			
    		@Html.ValidationMessageFor(Function(model) model.Admin)
    		</div>
    		@Html.HiddenFor(Function(model) model.Id)
    		@Html.HiddenFor(Function(model) model.DataCadastro)
    		<input type="submit" value="Editar" class="orange btn" />
    	</form>
    </div>
    
    @code
    	db.Dispose
    End Code

    When editing, it comes to this Action:

    <HttpPost()>
            Function Editar(Usuario As Usuario) As ActionResult
                ModelState.Remove("Fornecedor.Nome")
                If ModelState.IsValid Then
                    Usuario.Fornecedor = db.Fornecedores.Find(Usuario.Fornecedor.Id)
                    db.Entry(Usuario).State = EntityState.Modified
                    db.SaveChanges()
                    LogIndicadoresBmg.EntradaLog("Usuário " + Usuario.Id.ToString + " editado", Convert.ToInt32(Session("IdUsuário")))
                    Return RedirectToAction("Indice")
                End If
    
                Return View(Usuario)
            End Function


    Here's the problem: the Fornecedor property (which is another Entity in this context) is never updated!

    Am I missing something? The object passed on db.Entry seems correct.

    Here are the Entities used in this update view:

    <Table("Usuarios")>
        Public Class Usuario
            Implements IIdentity
            Public Overridable Property Id As Integer
            <Required(ErrorMessage:="E-mail não pode ser vazio.")>
            <StringLength(50, ErrorMessage:="E-mail deve possuir até 20 caracteres.")>
            Public Overridable Property Email As String
            <Required(ErrorMessage:="Senha não pode ser vazia.")>
            Public Overridable Property Senha As String
            Public Overridable Property Empresa As String
            Public Overridable Property Admin As Boolean = False
            Public Overridable Property Fornecedor As Fornecedor
    
            Public Overridable Property DataCadastro As DateTime
    
    
            <NotMapped()>
            Public ReadOnly Property Name() As String Implements IIdentity.Name
                Get
                    Return Email
                End Get
            End Property
    
            <NotMapped()>
            Public ReadOnly Property AuthenticationType() As String Implements IIdentity.AuthenticationType
                Get
                    Return "Custom"
                End Get
            End Property
    
            <NotMapped()>
            Public ReadOnly Property IsAuthenticated() As Boolean Implements IIdentity.IsAuthenticated
                Get
                    Return Not String.IsNullOrWhiteSpace(Email)
                End Get
            End Property
        End Class

    <Table("Fornecedores")>
        Public Class Fornecedor
    
            Public Overridable Property Id As Integer
            <Required(ErrorMessage:="Nome do fornecedor não pode ser vazio.")>
            Public Overridable Property Nome As String
            Public Overridable Property DataCriacao As DateTime
            Public Overridable Property Usuarios As ICollection(Of Usuario)
        End Class


    -Pedro Luz

    Friday, March 23, 2012 3:53 PM

Answers

  • Hi Pedro C Luz,

    Welcome to MSDN Forum.

    Based on the code, the relationship between "Fornecedores" and "Usuarios" is one to many, so if you create the database with the code, a foreign key will be auto-generated by EF in the "Usuarios" database table. Do you mean, after assigning the exist "Fornecedores" entity to the "Usuarios", and calling SaveChanges, the foreign key doesn't modified? If I understand correctly, first, please try to check the entity which you queried out from the database by the "Find" method is what you want; Second, check the final "Usuarios" entity's "Fornecedores" property, and make sure whether it has already changed; After that, if both of them are no problem, you needn't modify the entity state manually, EF will help you to do that; Finally, call SaveChanges method. If after complete all the steps above, the foreign key is still not changed, please check the T-SQL which generated by EF in SQL Profiler, make sure whether the update command is correct.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Monday, March 26, 2012 5:42 AM
    Moderator