Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ InsertOnSubmit: NullReferenceException

I have this code:

using DC = MV6DataContext;
using MV6; // Business Logic Layer
// ...

public DC.MV6DataContext dc = new DC.MV6DataContext(ConnectionString);
IP ip = new IP(Request.UserHostAddress);
dc.IPs.InsertOnSubmit(ip);
dc.SubmitChanges();

// in Business Logic layer:
public class IP : DC.IP {
  public IP(string address) { ... }
}

Upon attempting to InsertOnSubmit(ip), I get a NullReferenceException (Object reference not set to an instance of an object). dc is not null; ip and all properties of ip are not null; though some are empty.

VS2008 won't let me step into InsertOnSubmit, so I have no way of knowing what specifically is null when being evaluated. What gives?

Note: I have checked, and all Linq.EntitySets created by FK relationships are present and non-null.

like image 549
tsilb Avatar asked Jan 31 '09 19:01

tsilb


2 Answers

Actually it's better to add a call to your constructor that also calls the generic constructor such as:

public IP(string address) : this() {
...
}
like image 86
Max Avatar answered Oct 18 '22 10:10

Max


Got it.

Rather than creating a class that inherits from the DataContext's class, I extend the DC class itself with a partial class in the Business Logic layer. From there I can add whatever constructors and methods I wish.

In this case, it is neccessary to copy the code from the existing (auto-generated) constructor:

public IP(string address) {
Address = address;
Domain = "";
Notes = "";
FirstAccess = DateTime.Now;
LastAccess = DateTime.Now;
this._Sessions = new EntitySet<Session>(new Action<Session>(this.attach_Sessions), new Action<Session>(this.detach_Sessions));
OnCreated(); }

Not sure what's in that OnCreated handler, but it seems to be doing the work that boned me earlier. Works fine now :)

like image 36
tsilb Avatar answered Oct 18 '22 08:10

tsilb