简体   繁体   English

LINQ to Entities-更新二进制字段

[英]LINQ to Entities - updating binary field

I have LINQ to Entities set up with MySQL. 我已经使用MySQL设置了LINQ to Entities。

One field is a binary type, for example varbinary(50). 一个字段是二进制类型,例如varbinary(50)。

LINQ to Entities returns this correctly as a byte[]. LINQ to Entities将其正确返回为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. 但是,如果仅更改byte []中一个索引的值,则在调用SaveChanges()时,更改不会传播到数据库。

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)? 例如,要将那个byte []标记为脏(或更好的解决方案)?

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). 我怀疑它正在寻找实际设置的属性,以便将其标记为已修改,而不是修改属性的内容(就像您怀疑的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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