我正在尝试使用 LINQ to SQL 将新对象插入到我的数据库中,但是当我在下面的代码片段中调用 InsertOnSubmit() 时得到 NullReferenceException。我传入了一个名为 FileUploadAudit 的派生类,并设置了对象上的所有属性。
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"
我已经像这样添加到 Audit 类中:
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; }
}
任何想法是什么问题?我能找到的最接近的问题是在这里,但我的部分审计类在生成的代码中调用无参数构造函数,我仍然遇到问题。
更新:
只有当我传入派生的 FileUploadAudit 类时才会出现此问题,Audit 类工作正常。Audit 类作为 linq to sql 类生成,并且没有属性映射到派生类中的数据库字段。