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; }
}
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.