1

I'm new in entity framework. Have a code:

public Owner AddOwnerForProduct(int productId, string ownerName)
{
    using (var context = new Entities())
    {
        var existingOwner = context.Owners
            .SingleOrDefault(owner => owner.ProductId == productId);
        if (existingOwner != null)
            return existingOwner;

        var newOwner = new Owner
        {
            ProductId = productId,
            Name = ownerName
        };

        context.Owners.Add(newOwner);
        context.SaveChanges();

        return newOwner;
    }
}

The Owner can be only one. If the Owner for ProductId already exists should be returned an existing Owner entity. What do I need to add in the code if I know that it is possible more than one method call at a time (multithreading) for the same productId? I think not lock statement?

Hopeless
  • 579
  • 1
  • 8
  • 25
  • From an application POV this code is safe, however, you will probably want to look at the [optimistic concurrency patterns](https://msdn.microsoft.com/en-us/data/jj592904) that are recommended for use with EF. – spender Feb 18 '16 at 15:44
  • Maybe [my answer here](http://stackoverflow.com/a/35223997/3410196) can help. – Alexander Derck Feb 18 '16 at 15:45
  • Is it a 1-on-1 relation in your model/code? Do you have a navigational property? This kind of data-integrity is better solved in the database using a unique constraint I think. – Maarten Feb 18 '16 at 15:59
  • Can owners only own one product? If so, you should also check for unique names. But I think a one-to-many association is more appropriate here. – Gert Arnold Feb 19 '16 at 23:29

0 Answers0