Khi tôi chạy đoạn mã sau, tôi nhận được một NullReferenceException nói rằng một tham chiếu đối tượng không được đặt thành một thể hiện của đối tượng. Tôi đã chèn thành công với dapper bằng cách sử dụng các đối tượng ít phức tạp hơn nhưng cùng định dạng, vì vậy tôi không chắc chắn những gì tôi đang làm sai.NullReferenceException khi chèn với Dapper
public void Foo(IEnumerable<FogbugzCase> cases)
{
// using a singleton for the SqlConnection
using (SqlConnection conn = CreateConnection())
{
foreach (FogbugzCase fogbugzCase in cases)
{
conn.Execute("INSERT INTO fogbugz.Cases(CaseId, Title, ProjectId, CategoryId, Root, MilestoneId, Priority, Status, EstimatedHours, ElapsedHours, AssignedTo, ResolvedBy, IsResolved, IsOpen, Opened, Resolved, Uri, ResolveUri, OutlineUri, SpecUri, ParentId, Backlog) VALUES(@BugId, @Title, @ProjectId, @CategoryId, @RootId, @MilestoneId, @Priority, @StatusId, @EstimatedHours, @ElapsedHours, @PersonAssignedToId, @PersonResolvedById, @IsResolved, @IsOpen, @Opened, @Resolved, @Uri, @ResolveUri, @OutlineUri, @Spec, @ParentId, @Backlog);", new {BugId = fogbugzCase.BugId, Title = fogbugzCase.Title, ProjectId = fogbugzCase.Project.Id, CategoryId = fogbugzCase.Category.Id, RootId = fogbugzCase.Root, MilestoneId = fogbugzCase.Milestone.Id, Priority = fogbugzCase.Priority, StatusId = fogbugzCase.Status.Id, EstimatedHours = fogbugzCase.EstimatedHours, ElapsedHours = fogbugzCase.ElapsedHours, PersonAssignedToId = fogbugzCase.PersonAssignedTo.Id, PersonResolvedById = fogbugzCase.PersonResolvedBy.Id, IsResolved = fogbugzCase.IsResolved, IsOpen = fogbugzCase.IsOpen, Opened = fogbugzCase.Opened, Resolved = fogbugzCase.Resolved, Uri = fogbugzCase.Uri, OutlineUri = fogbugzCase.OutlineUri, Spec = fogbugzCase.Spec, ParentId = fogbugzCase.ParentId, Backlog = fogbugzCase.Backlog});
}
}
}
đầu tiên tôi đã cố gắng làm những cách đơn giản hơn vì chỉ đi qua trong fogbugzCase
thay vì đối tượng ẩn danh nhưng dẫn đến một ngoại lệ khác nhau về CategoryID.
Bất cứ ai nhìn thấy những gì tôi bị thiếu?
Đặt điểm ngắt và kiểm tra tất cả các đối tượng của bạn. Nếu tôi phải đoán, dựa trên những gì bạn nói về CategoryId, 'fogbugzCase.Category' có thể là null. Nhưng kiểm tra mọi thứ. Nếu bạn truy cập thuộc tính của tham chiếu null, bạn sẽ nhận được 'NullReferenceException'. – zimdanen
@zimdanen thx, có điều gì đó vô giá trị - chỉ cố gắng tìm cách để kiểm tra điều đó ngay bây giờ. –
Hầu như tất cả các trường hợp của 'NullReferenceException' đều giống nhau. Vui lòng xem "[NullReferenceException trong .NET là gì?] (Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" để biết một số gợi ý. –