Niek de Klein
Niek de Klein

Reputation: 8834

How can I get an ICollection property out of a IRecord?

I have an IRecord which contains an ICollection of Samples. The ICollection looks like this:

Sample sample1 = scope.DbContext.Samples.AddNew(new Sample 
        { 
            Name = GenerateName("Sample one"),
            Tests = tests
        });

Sample sample2 = scope.DbContext.Samples.AddNew(new Sample 
    { 
        Name = GenerateName("Sample two"),
        Tests = tests
    });

ICollection<Sample> samples = new Collection<Sample>();
samples.Add(sample1);
samples.Add(sample2);

Then I add the samples to the record:

Order record = scope.DbContext.Orders.AddNew(new Order 
{ 
    Name = GenerateName("Order"),
    Samples = samples 
});

Now I want to get the Samples out of the record. I know that when I do

object name = record["Name"];

I get the correctly generated name. However, when I do

object propertyValue = record["Samples"];

it has no items in it. I want to do the following:

object propertyValue = record["Samples"];
if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType()))
{
    foreach (var property in (IEnumerable<IRecord>)propertyValue)
    {
        var test = property;
    }
}

So why does record["Samples"] not get the ICollection?

Upvotes: 0

Views: 293

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67115

It looks to me, that what you really want to use is the as keyword.

var samples = record["Samples"] as ICollection<Sample>;

However, why aren't you just using the CLR static type?

var samples = record.Samples;

Maybe I am just not understanding what you are trying to do here, but it seems like it can be boiled pretty simply to the above.

Upvotes: 1

Related Questions