Reputation: 184
I was told by JL herself I needed to disable lazy loading and remove virtuals from my code, so:
I. The Domain:
public class Parent
{
public int Id { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public int FK_ParentId { get; set; }
[ForeignKey("FK_ParentId")]
public Parent Parent { get; set; }
}
II. DAL:
public DataContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
III. program.cs
var clientSvc = new ClientSvcRef.ServiceClient();
var parent = new Parent();
var child = new Child {Parent = parent};
parent.Children.Add(child);
clientSvc.AddParent(parent);
The problem: Line 4 in program.cs: "Object reference not set to an instance of an object."
Upvotes: 2
Views: 2013
Reputation: 726509
There are at least two ways to deal with this issue:
(1) initialize collection yourself in the constructor,
public Parent() {
Children = new List<Child>();
}
or (2) use Create()
instead of new
:
var p = _db.Parents.Create();
var c = _db.Children.Create();
c.Parent = p;
Upvotes: 4