Reputation: 9234
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?
Upvotes: 0
Views: 917
Reputation: 59101
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();
};
Upvotes: 1
Reputation: 887215
You need to initialize the property to hold a collection instance in the constructor:
Items = new HashSet<TransactionItems>();
Upvotes: 2