0

Code:

Something smt = new Something(){
Prop = 123,
Prop2 = "asdad"
}

foreach(var related in relatedsomething)
{
    smt.Related.Add(new Related(){
    relatedprop = 123,
    };
}

Runtime gives me an error about null reference. Related is virtual Icollection. no foreign key fields in entities defined.

on contrary if I do

foreach(var related in relatedsomething)
{
db.Related.Add(new Related(){
    relatedprop = 123,
    Something = smt
    };
}

It works.
Although, I Want it to work as in first snippet.
Am I doing something wrong? 'Cos in shipped EF4 it works both ways.

model classes (relevant part):

public class Printer
{
    public int Id { get; set; }
    public string  Name { get; set; }
    public virtual ICollection<Replica> Replicas { get; set; }


}
public class Replica
{
    public int Id { get; set; }
    public virtual Printer Printer { get; set; }


}


public class PrintersContext: DbContext
{
    public DbSet<Printer> Printers { get; set; }
    public DbSet<Replica> Replicas { get; set; }

}
Alexander Taran
  • 6,655
  • 2
  • 39
  • 60

2 Answers2

0

I think I might have run into the same problem. I posted on MSDN, but got no response.

It's probably a bug in EF, which you have to live with and work around.

Mas
  • 4,546
  • 5
  • 39
  • 56
0

With code first you got to initiate your collections in constructor.

 class printer
 {
   public virtual ICollection<replica> replicas {get;set;}
    public printer{
      replicas = new HashSet<replica>();
    }
 }

and it'll all magically work again.

Alexander Taran
  • 6,655
  • 2
  • 39
  • 60