Pergunta

I am trying to update an object of class Transaction

    public int Id { get; set; }
    public System.DateTime Date { get; set; }
    public string Remarks { get; set; }
    public double Amount { get; set; }
    public Nullable<long> GroupId { get; set; }
    public long UserId { get; set; }

    public virtual ICollection<User> PaidForUsers { get; set; }
    public virtual User PaidByUser { get; set; }

The element PaidForUsers is a collection of the User object

    public long Id { get; set; }
    public long UserId { get; set; }

Here Id is auto generated and UserId is to be supplied by code.

What I am trying to do is, whenever I create a new transaction, I should create a new User only if the user is not present already in the database.

I am currently using DbContext.Transactions.Add(new transaction). This obviously creates a new user in the database everytime I create a new transaction.

The solution that I have adopted currently is to use a custom stored procedure only for the User Entity which tries to do the same thing. But I get the following error in that also

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

Here is the stored procedure -

ALTER PROCEDURE [dbo].[InsertUser]
    (@UserId bigint )
AS
declare @val bigint
declare @countza int

SELECT @val= Id  FROM dbo.Users1 where UserId = @UserId
set @countza = @@Rowcount

    if @countza = 0
    begin
    insert into dbo.Users1 (UserId) values (@UserId)
    select [Id] from [dbo].[Users1] 
            where @@ROWCOUNT > 0 and [Id] = scope_identity() 

    end
    else
    begin
        SELECT  'Id' = @val
    end

Can some one tell what is the best way to do this? Is creating a stored procedure the right way to go about it?

Foi útil?

Solução

I'd say the right way - under "normal" circumstances - is to use LINQ:

(I'm assuming that UserId must be unique, but is not the primary key (which is Id))

var transaction = context.Transactions.Create();
var user = context.Users.SingleOrDefault(u => u.UserId == userId);
if (user != null)
    transaction.PaidForUsers.Add(user);
else
    transaction.PaidForUsers.Add(new User { UserId = userId });
context.Transactions.Add(transaction);
context.SaveChanges();

If your operation is very performance critical, then the right way might be a Stored Procedure.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top