LINQ InsertOnSubmit:NullReferenceException
- 作者: 烟花易冷3971624
- 来源: 51数据库
- 2022-12-08
问题描述
我有这个代码:
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 不为空;ip 和 ip 的所有属性都不为空;虽然有些是空的.
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,所以我无法知道在评估时具体是什么 null.什么给?
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 都存在且非空.
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.
在这种情况下,有必要从现有的(自动生成的)构造函数中复制代码:
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 :)
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
