我正在使用 LINQ to SQL、ASP.NET MVC 和 C#。我有一个名为genesisRepository
连接到数据库。
我有一个用名为 Stream 的对象表示的表。它的定义如下:
[Table]
public class Stream
{
[HiddenInput(DisplayValue = false)]
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public long StreamID { get; set; }
[Required(ErrorMessage = "Please enter a stream name")]
[Column]
public string StreamName { get; set; }
/* Other columns removed for brevity */
[Required(ErrorMessage = "Please enter a stream URL")]
[Column]
public string StreamUrl { get; set; }
private EntitySet<StreamEntry> _StreamEntry;
[System.Data.Linq.Mapping.Association(Storage = "_StreamEntry", OtherKey = "StreamID")]
public EntitySet<StreamEntry> StreamEntry
{
get { return this._StreamEntry; }
set { this._StreamEntry.Assign(value); }
}
private EntitySet<Stream2FieldTypes> _Stream2FieldTypes;
[System.Data.Linq.Mapping.Association(Storage = "_Stream2FieldTypes", OtherKey = "StreamID")]
public EntitySet<Stream2FieldTypes> Stream2FieldTypes
{
get { return this._Stream2FieldTypes; }
set { this._Stream2FieldTypes.Assign(value); }
}
}
我的控制器中有一个测试操作,用于在我的控制器中创建新记录Stream
table.
public ActionResult StreamTest()
{
// create new stream
var stream = new Genesis.Domain.Entities.Stream();
stream.StreamUrl = "url";
stream.StreamName = "name";
stream.StreamBody = null;
stream.StreamTitle = null;
stream.StreamKeywords = null;
stream.StreamDescription = null;
genesisRepository.CreateStream(stream);
return View("Index");
}
功能genesisRepository()
看起来像这样:
public long CreateStream(Stream stream)
{
streamTable.InsertOnSubmit(stream);
streamTable.Context.SubmitChanges();
return stream.StreamID;
}
执行 ActionResult 时出现空引用错误StreamTest()
。 genesisRepository 不为空。streamTable
不为 null,并且新创建的对象stream
显然也不为空。我唯一能想到的是空的是EntitySet<T>
定义外部关系的属性。
因此,我将 ActionResult 代码修改为:
public ActionResult StreamTest()
{
// create new stream
var stream = new Genesis.Domain.Entities.Stream();
stream.Stream2FieldTypes = new EntitySet<Stream2FieldTypes>(); // new
stream.StreamEntry = new EntitySet<StreamEntry>(); // new
stream.StreamUrl = "url";
stream.StreamName = "name";
stream.StreamBody = null;
stream.StreamTitle = null;
stream.StreamKeywords = null;
stream.StreamDescription = null;
genesisRepository.CreateStream(stream); // CreateStream() returns ID as long
return View("Index");
}
但是当我尝试这样做时,我收到了这个错误:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 58: {
Line 59: get { return this._Stream2FieldTypes; }
Line 60: set { this._Stream2FieldTypes.Assign(value); } <-- the offending line
Line 61: }
Line 62:
Source File: C:\path\to\Stream.cs Line: 60
我可以使用创建新记录streamTable.Context.ExecuteCommand("INSERT INTO genesis.dbo.Stream (StreamName, StreamUrl) VALUES ('Name', 'url');");
.
我不明白如何从这里继续前进。我怎样才能简单地创建一个新记录Stream
?