我試圖插入一個新的對象到我的數據庫使用LINQ to SQL,但得到一個NullReferenceException當我調用下面的代碼片段中的InsertOnSubmit()。我傳入一個名爲FileUploadAudit的派生類,並且設置了該對象上的所有屬性。NullReferenceException當在Linq中調用InsertOnSubmit到SQL
public void Save(Audit audit)
{
try
{
using (ULNDataClassesDataContext dataContext = this.Connection.GetContext())
{
if (audit.AuditID > 0)
{
throw new RepositoryException(RepositoryExceptionCode.EntityAlreadyExists, string.Format("An audit entry with ID {0} already exists and cannot be updated.", audit.AuditID));
}
dataContext.Audits.InsertOnSubmit(audit);
dataContext.SubmitChanges();
}
}
catch (Exception ex)
{
if (ObjectFactory.GetInstance<IExceptionHandler>().HandleException(ex))
{
throw;
}
}
}
這裏的堆棧跟蹤:
at System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity)
at XXXX.XXXX.Repository.AuditRepository.Save(Audit audit)
C:\XXXX\AuditRepository.cs:line 25"
我已經添加到審計類是這樣的:
public partial class Audit
{
public Audit(string message, ULNComponent component) : this()
{
this.Message = message;
this.DateTimeRecorded = DateTime.Now;
this.SetComponent(component);
this.ServerName = Environment.MachineName;
}
public bool IsError { get; set; }
public void SetComponent(ULNComponent component)
{
this.Component = Enum.GetName(typeof(ULNComponent), component);
}
}
和派生FileUploadAudit看起來是這樣的:
public class FileUploadAudit : Audit
{
public FileUploadAudit(string message, ULNComponent component, Guid fileGuid, string originalFilename, string physicalFilename, HttpPostedFileBase postedFile)
: base(message, component)
{
this.FileGuid = fileGuid;
this.OriginalFilename = originalFilename;
this.PhysicalFileName = physicalFilename;
this.PostedFile = postedFile;
this.ValidationErrors = new List<string>();
}
public Guid FileGuid { get; set; }
public string OriginalFilename { get; set; }
public string PhysicalFileName { get; set; }
public HttpPostedFileBase PostedFile { get; set; }
public IList<string> ValidationErrors { get; set; }
}
任何想法是什麼問題?我能找到的最接近的問題是here,但我的部分Audit類正在調用生成的代碼中的無參數構造函數,而且我仍然遇到問題。
UPDATE:
此問題只當我通過在派生類FileUploadAudit發生,審計類工作正常。 Audit類是作爲linq to sql類生成的,並且沒有將屬性映射到派生類中的數據庫字段。
您可以張貼在堆棧跟蹤例外? – 2009-10-15 13:17:54
添加了堆棧跟蹤,但它沒有多大幫助 – Charlie 2009-10-15 13:34:11