Search code examples
servicestackormlite-servicestack

Servicestack ORMLite update child collection


I can see you can do stuff like this in ORMLite:

var customer =  new Customer {
    Name = "Customer 1",
    PrimaryAddress = new CustomerAddress {
        AddressLine1 = "1 Australia Street",
        Country = "Australia"
    },
    Orders = new[] {
        new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
        new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
    }.ToList(),
};

db.Save(customer, references:true);

But what about updating child collections?

How is this done?

To expand on this.

I have a UserAccount class and an Image class internal to UserAccount:

public class UserAccount 
{
    [AutoIncrement]
    public int Id {
        get ;
        set;
    }

    public UserAccount()
    {
        Images = new List<UserImage>();
    }

    public List<UserImage> Images { get; protected set; }

    public UserImage Image { get; set; }

    public class UserImage
    {
        public UserImage()
        {
            Created = DateTime.Now;
        }

        public UserImage(string name)
        {
            Value = name;
            Created = DateTime.Now;
        }

        public string Value { get; set; }
    }
}

Doing this:

var fullImage = new UserAccount.UserImage(newImageUrl);
fullImage.IsDefault = true;
user.Image = fullImage;
db.Update (fullImage);

Doesn't work.

Doing this:

var fullImage = new UserAccount.UserImage(newImageUrl);
fullImage.IsDefault = true;
user.Images.Add(fullImage);
db.Update (fullImage);

Doesn't work...

Also doing the same but having image as a seperate entity with it's own ID and setting reference on the parent class doesn't work?


Solution

  • I think this is the way:

    var image = new UserImage(newImageUrl);
    image.IsDefault = true;
    db.Save (image);
    
    var images = user.Images;
    images.Add (image);
    
    db.Update (new UserAccount{Id = user.Id, Image = image, Images = images});
    

    I hope I am wrong because that is so ugly :/

    [UPDATE]

    I have it looking like this now which is much nicer:

    db.UpdateOnly (user, 
        onlyFields: a=> new { a.Image, a.Images}, 
        where: ua => ua.Id == user.Id);