mercredi 25 janvier 2017

If and Else firing on same object with C# Entity Framework lookup value

I have a feeling some of you will say this is impossible, however I have logs showing that the if and else statement are firing on the same object. Is there a legitimate reason for this or is it just acting up?

public void UpdateDirectoryEntry(DirectoryEntry adObj)
{
    using (PowerSource_DataEntities entities = new PowerSource_DataEntities())
    {
        PSObject pso = DirectoryEntrytoPSObject(adObj);
        PSObject curObject = entities.PSObjects.FirstOrDefault(x => x.DistinguishedName == dn);
        if (curObject != null)
        {
            AppLog.InfoLog(
                            string.Format("Updating object in database: {0} - {1}", pso.DistinguishedName,
                                            pso.DisplayName), true);
            pso.LastCheck = DateTime.Now;
            pso.Id = curObject.Id;
            entities.Entry(curObject).CurrentValues.SetValues(pso);
            entities.SaveChanges();

        }
        else
        {
            AppLog.InfoLog(string.Format("Adding new object to database: {0} - {1}", pso.DistinguishedName,
                                    pso.DisplayName), true);
            pso.LastCheck = DateTime.Now;
            entities.PSObjects.Add(pso);
            entities.SaveChanges();

        }
    }
}

The reason why I know is that I have logs that show the same object being updated in the database and added to the database as a duplicate one right after the other, when there is only one instance of the method running.

Also, I was able to fix it by putting a return in after the entities.SaveChanges(). I am fine with the fix, but I would like to know the logic behind this moving forward.

Aucun commentaire:

Enregistrer un commentaire