0

I made a test program for something totally unrelated to Entity Framework and what I thought would be an easy integration turned out to be troublesome. I have a DB Table called "TestEntry" which holds four data fields [ Id (uniqueidentifier), EId (uniqueidentifier), Name, Data ], these are unrelated to any other database tables and are standalone.

The issue is a simple update which is defined as such:

    EDMEntities _db = new EDMEntities();

    public List<TestEntry> GetEntities()
    {
        return _db.TestEntries.ToList();
    }
    public void EditEntry(TestEntry newEntry)
    {
        TestEntry entry = _db.TestEntries.FirstOrDefault(e => e.Id == newEntry.Id);
        if (string.IsNullOrEmpty(newEntry.Name)) { entry.Name = newEntry.Name; }
        if (string.IsNullOrEmpty(newEntry.Data)) { entry.Data = newEntry.Data; }

        if (entry.EntityState == System.Data.EntityState.Modified)
        {
            _db.SaveChanges();
        }
    }

After stepping through it I noticed:

  • Neither entry.Name nor entry.Data gets updated with the values from newEntry
  • The EntityState remains unchanged thus not entering the conditional

Any ideas on what this could be?

2 Answers 2

2

You need to negate the conditionals.

if (!string.IsNullOrEmpty(newEntry.Name))

Note the exclamation mark.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean entry.EntityState != System.Data.EntityState.Modified as that would still not yield any results because the actual entity does not get updated.
@Cosmin Parculescu: No. Where you are checking if the newEntity has values is the problem.
Sometimes it just takes a fresh pair of eyes to catch them.
2

Shouldn't it be:

if (!string.IsNullOrEmpty(newEntry.Name)) { entry.Name = newEntry.Name; }
if (!string.IsNullOrEmpty(newEntry.Data)) { entry.Data = newEntry.Data; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.