我有代码优先模型。我试图获取一个细节,从构造函数自动设置自己的详细信息编号。这是我到目前为止的地方:
public class Header
{
public Header()
{
Details = new List<Detail>();
}
[Key]
public Guid Id { get; set; }
[Required]
public Guid CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
public DateTime OrderDate { get; set; }
public ICollection<Detail> Details { get; set; }
}
这是细节:
public class Detail
{
public Detail(Guid id) : base()
{
HeaderId = id;
}
public Detail(Header header) : base()
{
Header = header;
}
private Detail()
{
DetailNumber = (Header.Details.Count) + 1;
}
[Key]
public Guid Id { get; set; }
[Required]
public Guid HeaderId { get; set; }
[ForeignKey("HeaderId")]
public virtual Header Header { get; set; }
public int DetailNumber { get; set; }
[Required]
public Guid ItemId { get; set; }
[ForeignKey("ItemId")]
public virtual InventoryItem Item { get; set; }
}
为什么设置DetailNumber时两个参数化构造函数都会抛出Null引用错误?
答案 0 :(得分:1)
使用此构造函数
public Detail(Guid id) : base()
{
HeaderId = id;
}
您的Header为null,因为它从未初始化。我认为在第二个问题上,:base()
在参数化构造函数初始化Header之前执行。
您可以稍微重新排列构造函数,以便在未传入构造函数时始终创建Header
。
public Detail() : this(Guid.NewGuid())
{
}
public Detail(Guid id) : this(new Header())
{
HeaderId = id;
}
public Detail(Header header)
{
Header = header;
DetailNumber = (Header.Details.Count) + 1;
}