views:

147

answers:

1

Hi,

I'm still learning here and have a question about child collections. I have an aggregate root called Audio, which has a collection of AudioDownloads.

The downloads are records of each IP address which downloads the audio, i don't want to have duplicate records of the same IP for each Audio.

In my domain i have the following function:

 public virtual void Add(AudioDownload download)
    {
        if (!AudioDownloads.Contains(download)) {
            TotalDownloads++;
            AudioDownloads.Add(download);
        }
    }

And this is how i am calling the Add function:

var download = new AudioDownload();
audio.Add(download);

This is returning all downloads from the database for this Audio (which chould be thousands!), also it's still adding the download even though one already exists.

I'm using S#arp with the DomainSignature approach for comparing my entities.

Here is my Domain:

public class AudioDownload : Entity, ITenantSpecific
{
    public AudioDownload() { DateAdded = DateTime.Now; }

    [DomainSignature]
    public virtual Audio Audio { get; set; }

    [DomainSignature]
    public virtual string Ip { get; set; }

    public virtual DateTime DateAdded { get; set; }
}

My question is...even if i can get AudioDownloads not to add duplicate entries, should i be doing it this way at all?

Thank you very much!

Paul

+1  A: 

I expect that most ways to do this will always lead you to query all downloads from the database, which is probably not what you want.

Another approach that might be cheaper is just to have a unique key in the database defined based on AudioId and Ip. If you then insert a record that duplicates these you will get an exception from NHibernate telling you a unique key was violated: handle that exception gracefully (i.e. don't show it as an error, load the existing AudioDownload and use that in future) and you will have achieved your goal, I believe.

When you use this approach do not check whether the download is already contained in the collection, since that would still trigger loading of all records.

On the other hand: would it not be interesting to see that something was downloaded from the same Ip multiple times?

Fried Hoeben
Paul Hinett
If you want unique downloads per IP you could also write a 'distinct' query to count that number.On a side note: IPs are not really guaranteed to be used by the same person all the time. Some internet providers don't give their users the same IP at various points in time, so the value of the result might not be that high (your approach with logged in user is more reliable)...
Fried Hoeben
Paul Hinett