Cosmin Pârvulescu
Cosmin Pârvulescu

Reputation: 324

ASP.NET MVC3 Entity Framework Entity not updating correctly

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:

Any ideas on what this could be?

Upvotes: 0

Views: 434

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Shouldn't it be:

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

Upvotes: 2

Scott Munro
Scott Munro

Reputation: 13576

You need to negate the conditionals.

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

Note the exclamation mark.

Upvotes: 2

Related Questions