Duplicate entry created, but why? (linq to sql)

We have a table that stores newsletter subscriptions (ID, EmailAddress, MyNewsletter1, etc.), and when we save the subscription, we first check if there is already a subscription configured for this email address. If there is, we update this entry; if not, we insert a new one. For some reason, a duplicate email address made my way there, and I don’t know how to do it. The primary key is the identifier, so we can change it as EmailAddress, but I'm still interested in how this happened. Could this be a concurrency problem? This is the code:

public static void SaveSubscription(NewsletterSubscription subscription)
{
    using (MyDataContext db = new MyDataContext())
    {
        // does this email already have subscriptions?
        NewsletterSubscription result = db.NewsletterSubscriptions.SingleOrDefault(r => r.Email == subscription.Email);

        if (result != null)
        {
            // update instead of creating new record
            result.MyNewsletter1 = subscription.MyNewsletter1;
            result.MyNewsletter2 = subscription.MyNewsletter2;
            result.MyNewsletter3 = subscription.MyNewsletter3;
            result.MyNewsletter4 = subscription.MyNewsletter4;
        }
        else
        {
            // create new subscription record
            subscription.RegisterDate = DateTime.Now;
            db.NewsletterSubscriptions.InsertOnSubmit(subscription);
        }

        db.SubmitChanges();
    }
}

Thank,

Anneli

+3
source share
3 answers

, , /. :

using (var tran = new TransactionScope()) { 
    using (MyDataContext db = new MyDataContext()) {
        // ... your existing code here
    }
    tran.Complete();
}

, , , ; SPID, " ", ; SPID , ; SPID , ( ) ( Complete ), SPID.

, , - . , .

+2

, , , concurrency, . , .

+2

, concurrency. , / .

SubmitChanges , . catch ( , ) .

, , .

+1

Source: https://habr.com/ru/post/1794701/


All Articles