2

Learning ropes with LINQ here, well experienced with classic SQL and ADO.

Before I go on with my project and make any type changes too expensive, please let me know what the correct way is to use the varbinary columns. How should they be declared with LINQ? What type it should map to in order not to cause any pain.

Right now I have tested mapping to byte[] array, and it works pretty well with some initial testing. I plan to store data gathered from streams, and since the contents of streams can be got in byte array format via ToArray() method, this approach seems to be viable.

private byte[] _testVarbinary;
[Column(Storage="_testVarbinary")]
public byte[] testVarbinary
{
    get
    {
        return this._testVarbinary;
    }
    set
    {
        this._testVarbinary = value;
    }
}

...

// Reading
Console.WriteLine("Field size: {0}", f.testVarbinary.Length);

// Updating
f.testVarbinary = new byte[]{128, 129, 130, 131};
db.SubmitChanges();

So, should I map to some other, more LINQ-esque type instead? Or sticking with basic byte[] is just fine.

1 Answer 1

1

byte[] should work just fine, but you can use the Linq.Binary class also if you prefer. It represents an immutable block of bytes (byte[] is mutable).

Using f.testVarbinary[0] = 123; won't work for modifying a record's value because the entity is only tracking the property, testVarbinary, not every element of the array. You can probably just mark the property as modified just by calling the property setter, as in:

f.testVarbinary = f.testVarbinary;

However, the standard way of doing this is:

DbEntityEntry<MyEntity> entry = context.Entry(f);
entry.Property(e => e.testVarbinary).IsModified = true;

Or to mark the entire entity as modified, use:

entry.State = EntityState.Modified;
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so, if I am not going to update separate byte values, then Linq.Binary would be a more restrictive type to use? Actually, I tried to update a single element with byte[], ie f.testVarbinary[0]=123; db.SubmitChanges(); but it did not cause any change in the database value. I guess it did not trigger some internal "changed" flag, and perhaps there is some way to trigger it manually.
@Passiday I've updated my answer to include the relevant details for manually marking an entity or it's properties as modified.

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.