[英]Creating object with related objects in Entity Framework 4.1
I have the following database tables/EF objects 我有以下数据库表/ EF对象
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 我需要做的是为它的Items属性创建一个新的Transaction实例以及TransactionItems的几个实例,并将所有这些实例保存到我的数据库中
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循环中,我遍历一个集合并为每个成员创建一个新的TransactionItem,然后尝试将其添加到跨对象Item集合中
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. 尝试将transactionITem添加到我的Transaction对象的Item集合时,我得到一个空引用异常。 What am I doing wrong?
我究竟做错了什么?
您需要初始化属性以在构造函数中保存集合实例:
Items = new HashSet<TransactionItems>();
Did you ever Initialize TransactionItems
in the constructor for Transaction
or in your actual code? 你有没有初始化
TransactionItems
在构造函数用于Transaction
或在您的实际代码?
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();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.