Search code examples
codefluent

EntityState in update?


What is the correct approach while updating a record in CFE ?

We are using webapi controllers, based on this link, the client-side is developped thanks to AngularJS. I am having troubles updating a record that already exists and my code fails with an CodeFluentDuplicateException.

I read here that EntityState shouldn't be changed manually. When I want to update a server version with the client changes, shall I consider:

  • Taking the server version and then applying changes made by client ?
  • Ask the client version to Save() ?
  • Any other approach ?

Thanks for your answer,


Solution

  • CodeFluentDuplicateException means that you are inserting a record that already exists in the database. This occurs when the stored procedure executes an INSERT statement instead of an UPDATE. CodeFluent Entities don't use the EntityState to choose whether the entity must be created or updated in the database. Depending on your model, it uses the RowVersion property (insert if null; update otherwise). If there are no way to choose, the stored procedure executes an UPDATE and when no rows are updated it inserts the row. For instance:

    CREATE PROCEDURE [dbo].[Role_Save]
    (
     @Role_Id [uniqueidentifier],
     @Role_Name [nvarchar] (256),
    )
    AS
    SET NOCOUNT ON
    IF(@_rowVersion IS NOT NULL)
    BEGIN
        UPDATE [Role] SET
         [Role].[Role_Name] = @Role_Name
            WHERE (([Role].[Role_Id] = @Role_Id) AND ([Role].[_rowVersion] = @_rowVersion))
    END
    ELSE
    BEGIN
        INSERT INTO [Role] (
            [Role].[Role_Id],
            [Role].[Role_Name])
        VALUES (
            @Role_Id,
            @Role_Name)
    END
    

    So in your case I would check the code of the generated stored procedure to understand why it tries to insert the record instead of updating it.

    In fact you can change the EntityState manually if you need to, but there are only a few reasons to do it.