在Entity Framework 4.1中使用相关对象创建对象

时间:2011-11-07 21:45:01

标签: c# .net entity-framework entity-framework-4.1

我有以下数据库表/ EF对象

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

}

public class TransactionItems
{
    //some properties
}

我需要做的是,为其Items属性创建一个新的事务实例以及TransactionItems的几个实例,并将所有这些实例保存到我的数据库中

我尝试了以下内容:

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

然后在foreach循环中,我循环遍历集合并为每个成员创建一个新的TransactionItem并尝试将其添加到trans对象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...

}

当我尝试将transactionITem添加到Transaction对象的Item集合时,我得到一个空引用异常。我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要初始化属性以在构造函数中保存集合实例:

Items = new HashSet<TransactionItems>();

答案 1 :(得分:1)

您是否曾在TransactionItems的构造函数或实际代码中初始化Transaction

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

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

或者不太优先(除非你也做上述事情):

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