LINQ InsertOnSubmit:NullReferenceException异常 [英] LINQ InsertOnSubmit: NullReferenceException
问题描述
我有这样的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) { ... }
}
在试图InsertOnSubmit(IP),我得到一个NullReferenceException(不设置到对象的实例对象引用)。 DC不是null; IP和IP的所有属性都不为null;虽然有些是空的。
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不会让我踏进InsertOnSubmit,所以我不知道具体是什么为空进行评估时的方式。是什么给了?
VS2008 won't let me step into InsertOnSubmit, so I have no way of knowing what specifically is null when being evaluated. What gives?
请注意:我已经检查,并通过FK关系创建的所有Linq.EntitySets是present和非空
Note: I have checked, and all Linq.EntitySets created by FK relationships are present and non-null.
推荐答案
明白了。
而不是创建从DataContext中的类继承的类,我的DC类本身扩展与业务逻辑层的部分类。从那里,我可以添加我所希望的任何构造函数和方法。
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.
在这种情况下,这里有必要从现有(自动产生)构造复制code:
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(); }
不知道在这OnCreated处理程序,但它似乎是在做早去骨我的工作。现在工作得很好:)
Not sure what's in that OnCreated handler, but it seems to be doing the work that boned me earlier. Works fine now :)
这篇关于LINQ InsertOnSubmit:NullReferenceException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!