0

I have the following database tables/EF objects

public class Transaction
{
    //some other properties
    public ICollection<TransactionItems> Items {get; set;}

}

public class TransactionItems
{
    //some properties
}

What I need to do is, create a new instance of transaction along with several instances of TransactionItems for its Items property and save all of these to my DB

I have tried the following:

Transaction trans = new Transaction();
//set its properties

Then in a foreach loop I am looping through a collection and creating a new TransactionItem for each member and attempting to add it to the trans object Item Collection

foreach(var item in myCollection)
{

     TransactionItem newItem = new TransactionItem();
     //set its properties

     //add it to the tran Item collection
    tran.TransactionItems.Add(newItem);//getting null reference here...

}

I am getting a null reference exception when I attempt to add a transactionITem to the Item collection of my Transaction object. What am I doing wrong?

2 Answers 2

2

You need to initialize the property to hold a collection instance in the constructor:

Items = new HashSet<TransactionItems>();
Sign up to request clarification or add additional context in comments.

2 Comments

If you define it this way be careful that your Equals and GetHashCode operators specifically take the primary keys/unique constraint properties into consideration, and not other properties.
@MerlynMorgan-Graham: Or just use reference equality.
1

Did you ever Initialize TransactionItems in the constructor for Transaction or in your actual code?

public class Transaction
{
    public Transaction()
    {
        Items = new List<TransactionItems>();
    }

    //some other properties
    public ICollection<TransactionItems> Items {get; set;}
}

Or less preferrably (unless you also do the above):

Transaction trans = new Transaction()
{
    Items = myCollection.Select(
        item => new TransactionItem
        {
            // set its properties
        })
        .ToList();
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.