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; }
}
問題は何ですか?私が見つけることができる最も近い質問はhere ですが、私の部分的な Audit クラスは、生成されたコードでパラメーターなしのコンストラクターを呼び出していますが、それでも問題が発生します。
アップデート:
この問題は、派生した FileUploadAudit クラスを渡した場合にのみ発生し、Audit クラスは正常に動作します。Audit クラスは linq to sql クラスとして生成され、派生クラスのデータベース フィールドにマップされたプロパティはありません。