Saving entities

Jun 19, 2009 at 2:29 PM

I have a doubt regarding saving entities, let's say I have 2 classes: Money (Name:string, Abbreviation:string, DecimalPlaces:byte), Account (Bank:string, AccountNumber:string, Money:Money). Money has 1000 records but it will not change in time so I have static Id's. I want to save 100 accounts with diferent "Account.Money", how can I save the accounts without going 100 times to the DB for the Money? I tried to do the following :

new Account
{
    Bank = "ABC",
    AccountNumber = "123456",
    Money = new Money { Id = 1 }
}.Save();
but theres an error, Id is read only. So how can I do that?
Thanks!.
Ariel
Coordinator
Jun 19, 2009 at 7:23 PM
Edited Jun 19, 2009 at 8:44 PM

You have many options:

If Money's small enought to not make a perf. penalty when retrieving Accounts,

1.- ObjectCache (will be renamed to EntityCache in next version):

using(new ObjectCache())
{
  new Account
  {
    Bank = "ABC",
    AccountNumber = "123456",
    Money =  Database.Retrieve<Money>(1)
  }.Save();
}

Note that, just by creating an ObjectCache all the Database operations in the thread will keep track of IdentifieableEntities (like Money) keeping only one instance of each. Every atomic Database operation has an implicit ObjectCache (so if you do something like Database.RetrieveAll<Account>() you will have just one instance of US dollar).

2.- Manual Dictionary:

var moneys = Database.RetrieveAll<Money>().ToDictionary(m=>m.Id);

new Account
{
    Bank = "ABC",
    AccountNumber = "123456",
    Money = moneys[1]
}.Save();

3.- If Money's a heavy entity, Lazy<Money> will be a better idea, then you can just do:

new Account
{
    Bank = "ABC",
    AccountNumber = "123456",
    Money = new Lazy<Money>(1)
}.Save();

This is more similar to the code you where thinking of, but look how you have to change your entity to enable this escenario. SF is all about consistency in your business entities, If you have a Money object, you have a real one, cos maybe there are validations on it, otherwise you have an lazy.

PD: I think Currency is a better name than Money, but maybe you are writing it in another language.

Hope you having a good experience with SF.

Olmo