简体   繁体   中英

LINQ to Entities - updating binary field

I have LINQ to Entities set up with MySQL.

One field is a binary type, for example varbinary(50).

LINQ to Entities returns this correctly as a byte[].

However, if I just change the value of one index in the byte[], the change is not propagated to the database when SaveChanges() is called.

For example, this doesn't work:

byte[] foo = GetBinaryFromDatabase(context);
foo[0] = 42;
context.SaveChanges();

I can get it to save the changes by creating an entirely new byte array, copying it over and assigning it back rather than doing it in-place.

For example, this works:

byte[] foo = GetBinaryFromDatabase(context);
byte[] bar = new byte[foo.Length];
Array.Copy(foo, bar, foo.Length);
bar[0] = 42;
foo = bar;
context.SaveChanges();

Is there any way to make the change in-place without having to make a copy of the array, such that it propagates to the database? For example, to mark that byte[] as dirty (or a better solution)?

You can mark a property as modified like this:

var entry = context.Entry(foo);

if (entry.State == EntityState.Detached)
    context.Set<FooType>().Attach(entity);

entry.Property(e => e.ByteProperty).IsModified = true;

// Or this if your version of EF doesn't support the lambda version:
// entry.Property("ByteProperty").IsModified = true;

I suspect it is looking for the property actually being set in order to mark it as modified rather than modifying the contents of the property (like you suspect).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM