EF 4.1 Code First bug in Find/Update. Any workarou

2019-07-01 09:05发布

I've found a pretty nasty bug in EF 4.1 Code First. Assume we have this piece of code to retrieve an entity from the context and then update it with new values:

public T Update<T>(T toUpdate) where T : class
        {
            System.Data.Objects.ObjectContext objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)_context).ObjectContext;
            System.Data.Objects.ObjectSet<T> set = objectContext.CreateObjectSet<T>();
            IEnumerable<string> keyNames = set.EntitySet.ElementType
                                                        .KeyMembers
                                                        .Select(k => k.Name);
            var type = typeof(T);
            var values = keyNames.Select(c => type.GetProperty(c).GetValue(toUpdate, null)).ToArray();
            var current = _context.Set<T>().Find(values);
            if (current != null)
            {
                _context.Entry(current).CurrentValues.SetValues(toUpdate);
            }
            return current;
        }

Now assume that my entity has a single key property which is a string.

Working scenario: stored entity has key "ABCDE" and my toUpdate entity has same key "ABCDE": everything works fine.

Bug scenario: stored entity has key "ABCDE" and my toUpdate entity has key "ABCDE " (notice the space after the last letter).

The two keys are indeed different. But the find method "automagically" trims my key and finds the stored entity anyway. This would be good, if it didn't break the SetValues method: since the stored key and the new key are different, I get (rightly) the following:

The property 'Id' is part of the object's key information and cannot be modified.

Because, being different, it tries to update it, and since it's a key property it cannot be updated, so the whole thing fails and throws.

What I think is that the "Find" method shouldn't automagically trim the key values (or whatever it is doing internally to make the two different strings appear the same). In the second scenario, the "Find" method should return null.

Now two things: how do I workaround this temporarily, and where can I report this bug, because I couldn't find an official place to report the bug.

Thanks.

EDIT: Reported the bug here: https://connect.microsoft.com/VisualStudio/feedback/details/696352/ef-code-first-4-1-find-update-bug

1条回答
SAY GOODBYE
2楼-- · 2019-07-01 09:35

But the find method "automagically" trims my key and finds the stored entity anyway.

I dont' believe that trimming happens. Find uses a SingleOrDefault query internally, in other words: When you call...

set.Find("ABCDE "); // including the trailing blank

...it uses this LINQ query:

set.SingleOrDefault(key => key == "ABCDE "); // including the trailing blank

The problem is in the database and the result depends on the sort order, language, settings for capital/small letters, accents, etc. for your string key field in the database (nvarchar(10) for example).

For example if you use a standard Latin1_General sort order in SQL Server the key "ABCDE" and "ABCDE " (with trailing blank) are identical, you cannot create two rows which have these values as primary keys. Even "ABCDE" and "abcde" are identical (if you don't setup to distinguish capital and small letters in SQL Server).

At the same time this means that also queries for string columns will return all matching rows - matching with respect to the sort order of that column in the database. The query for "ABCDE " with trailing blank will just return a record with "ABCDE" without the trailing blank.

Up to this point this is "normal" behaviour for all LINQ to Entities queries which involve strings.

Now, it seems - as you found - that the ObjectContext doesn't know about the configured sort order in the database and uses the normal .NET string comparison where a string with and a string without trailing blank are different.

I don't know if it's possible to tell the context to use the same comparison of strings as the database. I have some doubt that this is possible because the .NET world and the relational database world are too different. Some sort orders might be special and only available in the database and not in .NET at all and vice versa perhaps. In addition there are also other databases than SQL Server which must be supported by Entity Framework and those databases might have their own sort order system.

For your specific case - and perhaps always when you have string keys - a possible fix of your problem would be to set the key property of the entity to update to the key of the object returned from the database:

toUpdate.Id = current.Id;
_context.Entry(current).CurrentValues.SetValues(toUpdate);

Or more generally in the context of your code:

//...
var current = _context.Set<T>().Find(values);
if (current != null)
{
    foreach (var keyName in keyNames)
    {
        var currentValue = type.GetProperty(keyName).GetValue(current, null);
        type.GetProperty(keyName).SetValue(toUpdate, currentValue, null);
    }
    _context.Entry(current).CurrentValues.SetValues(toUpdate);
}

toUpdate must not be attached to the context to get this working.

Is this a bug? I don't know. At least it is a consequence of a mismatch between .NET and relational database world and a good reason to avoid string key columns/properties in the first place.

查看更多
登录 后发表回答