Attachments: Copy, Move, Rename

Attachments can be copied, moved, or renamed using built-in session methods.
All of those actions are executed when SaveChanges is called and take place on the server-side,
removing the need to transfer the entire attachment binary data over the network in order to perform the action.

Copy attachment

Attachment can be copied using one of the session.Advanced.Attachments.Copy methods:

Syntax

void Copy(
    object sourceEntity,
    string sourceName,
    object destinationEntity,
    string destinationName);

void Copy(
    string sourceDocumentId,
    string sourceName,
    string destinationDocumentId,
    string destinationName);

Example

var employee1 = session.Load<Employee>("employees/1-A");
var employee2 = session.Load<Employee>("employees/2-A");

session.Advanced.Attachments.Copy(employee1, "photo.jpg", employee2, "photo-copy.jpg");

session.SaveChanges();
var employee1 = await asyncSession.LoadAsync<Employee>("employees/1-A");
var employee2 = await asyncSession.LoadAsync<Employee>("employees/2-A");

asyncSession.Advanced.Attachments.Copy(employee1, "photo.jpg", employee2, "photo-copy.jpg");

await asyncSession.SaveChangesAsync();

Move attachment

Attachment can be moved using one of the session.Advanced.Attachments.Move methods:

Syntax

void Move(object sourceEntity, string sourceName, object destinationEntity, string destinationName);

void Move(string sourceDocumentId, string sourceName, string destinationDocumentId, string destinationName);

Example

var employee1 = session.Load<Employee>("employees/1-A");
var employee2 = session.Load<Employee>("employees/2-A");

session.Advanced.Attachments.Move(employee1, "photo.jpg", employee2, "photo.jpg");

session.SaveChanges();
var employee1 = await asyncSession.LoadAsync<Employee>("employees/1-A");
var employee2 = await asyncSession.LoadAsync<Employee>("employees/2-A");

asyncSession.Advanced.Attachments.Move(employee1, "photo.jpg", employee2, "photo.jpg");

await asyncSession.SaveChangesAsync();

Rename attachment

Attachment can be renamed using one of the session.Advanced.Attachments.Rename methods:

Syntax

void Rename(object entity, string name, string newName);

void Rename(string documentId, string name, string newName);

Example

var employee = session.Load<Employee>("employees/1-A");

session.Advanced.Attachments.Rename(employee, "photo.jpg", "photo-new.jpg");

session.SaveChanges();
var employee = await asyncSession.LoadAsync<Employee>("employees/1-A");

asyncSession.Advanced.Attachments.Rename(employee, "photo.jpg", "photo-new.jpg");

await asyncSession.SaveChangesAsync();