在这一行 _repository.CreateDealer(d); 我收到以下错误。
我已经开始根据本教程的基础知识构建我的代码 http://www.dotnetcurry.com/ShowArticle.aspx?ID=786
Server Error in '/' Application.
--------------------------------------------------------------------------------
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 84: {
Line 85:
Line 86: _repository.CreateDealer(d);
Line 87: }
Line 88: //DataContractJsonSerializer jsonSerializer =
Source File: C:\Users\Scott\Documents\Visual Studio 2010\Projects\DealerTentSaleMVC\DealerTentSaleMVC\Controllers\EdmundsController.cs Line: 86
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
DealerTentSaleMVC.Controllers.EdmundsController.Create(String zip, String make) in C:\Users\Scott\Documents\Visual Studio 2010\Projects\DealerTentSaleMVC\DealerTentSaleMVC\Controllers\EdmundsController.cs:86
lambda_method(Closure , ControllerBase , Object[] ) +227
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8972317
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
DealerRepository.cs
public void CreateDealer(DealersTemp.DealerHolder dealer)
{
using (DealerContext context = new DealerContext())
{
context.Entry(new DealersTemp.DealerHolder
{
//DealerHolderId = dealer.DealerHolderId,
id = dealer.id,
locationId = dealer.locationId,
address = dealer.address,
name = dealer.name,
logicalName = dealer.logicalName,
type = dealer.type,
make = dealer.make,
operations = dealer.operations,
contactinfo = dealer.contactinfo,
publishDate = dealer.publishDate,
active = dealer.active,
syncPublishDate = dealer.syncPublishDate
}).State = System.Data.EntityState.Added;
context.SaveChanges();
}
}
IDealerRepository.cs
namespace DealerTentSaleMVC.Repository
{
public interface IDealerRepository
{
IEnumerable<DealersTemp.DealerHolder> GetAllDealers();
void CreateDealer(DealersTemp.DealerHolder dealer);
DealersTemp.DealerHolder ReadDealer(int id);
void UpdateDealer(DealersTemp.DealerHolder dealer);
void DeleteDealer(int id);
}
}
DealersTemp.cs
namespace DealerTentSaleMVC.Models
{
public class DealersTemp
{
public class Address
{
//public int AddressId { get; set; }
public string street { get; set; }
public string apartment { get; set; }
public string city { get; set; }
public string stateCode { get; set; }
public string stateName { get; set; }
public string county { get; set; }
public string country { get; set; }
public string zipcode { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
//public virtual int DealerHolderId { get; set; }
}
public class Operations
{
//public int OperationsId { get; set; }
public string Wednesday { get; set; }
public string Tuesday { get; set; }
public string Thursday { get; set; }
public string Saturday { get; set; }
public string Friday { get; set; }
public string Monday { get; set; }
public string Sunday { get; set; }
//public virtual int DealerHolderId { get; set; }
}
public class Contactinfo
{
//[Key]
//public int ContactinfoId { get; set; }
public string dealer_website { get; set; }
public string email_address { get; set; }
public string phone { get; set; }
//public string phone_areacode { get; set; }
//public string phone_postfix { get; set; }
//public string phone_prefix { get; set; }
//public virtual int DealerHolderId { get; set; }
}
public class DealerHolder
{
//[Key]
//public int DealerHolderId { get; set; }
public string id { get; set; }
public string locationId { get; set; }
public Address address { get; set; }
public string name { get; set; }
public string logicalName { get; set; }
public string type { get; set; }
public string make { get; set; }
public Operations operations { get; set; }
public Contactinfo contactinfo { get; set; }
public string publishDate { get; set; }
public bool active { get; set; }
public string syncPublishDate { get; set; }
public DealersTemp.DealerHolder ToDomainDealer()
{
return new DealersTemp.DealerHolder
{
//DealerHolderId = this.DealerHolderId,
id = this.id,
locationId = this.locationId,
address = this.address,
name = this.name,
logicalName = this.logicalName,
type = this.type,
make = this.make,
operations = this.operations,
contactinfo = this.contactinfo,
publishDate = this.publishDate,
active = this.active,
syncPublishDate = this.syncPublishDate
};
}
}
public class RootObject
{
public List<DealerHolder> dealerHolder { get; set; }
}
}
EdmundsController.cs
[HttpPost]
public ActionResult Create(string zip, string make)
{
string url = "http://api.edmunds.com/v1/api/dealer?zipcode=" + zip.Replace(" ", "") + "&makeName=" + make.Replace(" ", "") + "&radius=3000&fmt=json&api_key=SomeKey";
//WebRequest request = WebRequest.Create(url);
WebClient wc = new WebClient();
string stws = wc.DownloadString(url);
JToken root = JObject.Parse(stws);
JToken dealerholder = root["dealerHolder"];
DealerTentSaleMVC.Models.DealersTemp.DealerHolder convertedProducts = new DealerTentSaleMVC.Models.DealersTemp.DealerHolder();
string dh = dealerholder.ToString().Replace("[", "").Replace("]", "");
Result result = JsonConvert.DeserializeObject<Result>(stws);
foreach (DealersTemp.DealerHolder d in result.DealerHolder)
{
_repository.CreateDealer(d);
}
return RedirectToAction("Index");
}
DealerContext.cs
namespace DealerTentSaleMVC.Context
{
public class DealerContext: DbContext
{
public DbSet<DealersTemp.DealerHolder> Dealers { get; set; }
}
}
这是完整的 Json 字符串
{
"dealerHolder": [
{
"id": "31711",
"locationId": "3730",
"address": {
"street": "24825 US Hwy 19 N",
"apartment": "",
"city": "Clearwater",
"stateCode": "FL",
"stateName": "Florida",
"county": "Pinellas",
"country": "USA",
"zipcode": "33763",
"latitude": 27.99785,
"longitude": -82.729321
},
"name": "Countryside Ford of Clearwater",
"logicalName": "CountrysideFordofClearwater",
"type": "ROOFTOP",
"make": "Ford",
"operations": {
"Wednesday": "8:30 AM-9:00 PM",
"Tuesday": "8:30 AM-9:00 PM",
"Thursday": "8:30 AM-9:00 PM",
"Saturday": "8:30 AM-8:00 PM",
"Friday": "8:30 AM-9:00 PM",
"Monday": "8:30 AM-9:00 PM",
"Sunday": "11:00 AM-5:00 PM"
},
"contactinfo": {
"dealer_website": "http://www.clearwaterford.com/",
"email_address": "",
"phone": ""
},
"publishDate": "2012-05-25",
"active": true,
"syncPublishDate": "2012-05-25"
},
{
"id": "31673",
"locationId": "3708",
"address": {
"street": "2525 34th St N",
"apartment": "",
"city": "Saint Petersburg",
"stateCode": "FL",
"stateName": "Florida",
"county": "Pinellas",
"country": "USA",
"zipcode": "33713",
"latitude": 27.794484,
"longitude": -82.679411
},
"name": "Autoway Ford of St Petersburg",
"logicalName": "AutowayFordofStPetersburg",
"type": "ROOFTOP",
"make": "Ford",
"operations": {
"Wednesday": "08:30 AM-08:00 PM",
"Tuesday": "08:30 AM-08:00 PM",
"Thursday": "08:30 AM-08:00 PM",
"Saturday": "09:00 AM-06:00 PM",
"Friday": "08:30 AM-08:00 PM",
"Monday": "08:30 AM-08:00 PM",
"Sunday": "12:00 PM-05:00 PM"
},
"contactinfo": {
"dealer_website": "http://www.autowayford.net/",
"email_address": "",
"phone": ""
},
"publishDate": "2012-05-25",
"active": true,
"syncPublishDate": "2012-05-25"
},
{
"id": "31636",
"locationId": "3684",
"address": {
"street": "5815 N Dale Mabry Hwy",
"apartment": "",
"city": "Tampa",
"stateCode": "FL",
"stateName": "Florida",
"county": "Hillsborough",
"country": "USA",
"zipcode": "33614",
"latitude": 28.00016,
"longitude": -82.505206
},
"name": "Bill Currie Ford",
"logicalName": "BillCurrieFord",
"type": "ROOFTOP",
"make": "Ford",
"operations": {
"Wednesday": "8:00 AM-9:00 PM",
"Tuesday": "8:00 AM-9:00 PM",
"Thursday": "8:00 AM-9:00 PM",
"Saturday": "8:00 AM-8:00 PM",
"Friday": "8:00 AM-9:00 PM",
"Monday": "8:00 AM-9:00 PM",
"Sunday": "11:00 AM-6:00 PM"
},
"contactinfo": {
"dealer_website": "http://billcurriedirect.dealerconnection.com/",
"email_address": "",
"phone_areacode": "888",
"phone_postfix": "1156",
"phone_prefix": "255",
"phone": "8882551156"
},
"publishDate": "2012-05-25",
"active": true,
"syncPublishDate": "2012-05-25"
},
{
"id": "31723",
"locationId": "3739",
"address": {
"street": "17556 US 19 N",
"apartment": "",
"city": "Clearwater",
"stateCode": "FL",
"stateName": "Florida",
"county": "Pinellas",
"country": "USA",
"zipcode": "33764",
"latitude": 27.93164,
"longitude": -82.730647
},
"name": "Walker Ford",
"logicalName": "WalkerFord",
"type": "ROOFTOP",
"make": "Ford",
"operations": {
"Wednesday": "8:30 AM-8:00 PM",
"Tuesday": "8:30 AM-8:00 PM",
"Thursday": "8:30 AM-8:00 PM",
"Saturday": "8:30 AM-6:00 PM",
"Friday": "8:30 AM-8:00 PM",
"Monday": "8:30 AM-8:00 PM",
"Sunday": "11:30 AM-6:00 PM"
},
"contactinfo": {
"dealer_website": "http://www.walkerford.com/",
"email_address": "",
"phone_areacode": "727",
"phone_postfix": "3673",
"phone_prefix": "535",
"phone": "7275353673"
},
"publishDate": "2012-05-25",
"active": true,
"syncPublishDate": "2012-05-25"
}
]
}
以下是显示整个控制器代码的更新
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DealerTentSaleMVC.Models;
using System.Net;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using DealerTentSaleMVC.Repository;
namespace DealerTentSaleMVC.Controllers
{
public class EdmundsController : Controller
{
private static string GetApiKey() { return "AIzaSyDiOm4qmnR7ZPbPPiUJrIxfYZ0XreDMaW8"; }
private DealersTemp.RootObject db = new DealersTemp.RootObject();
private IDealerRepository _repository;
//
// GET: /Edmunds/
public ViewResult Index()
{
return View(_repository.GetAllDealers());
}
//
// GET: /Edmunds/Details/5
public ViewResult Details(int id)
{
DealersTemp.DealerHolder dealerholder = _repository.ReadDealer(id);
return View(dealerholder);
}
//
// GET: /Edmunds/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Edmunds/Create
public class Result
{
public ICollection<DealersTemp.DealerHolder>DealerHolder { get; set; }
}
//[HttpPost]
//public ActionResult Create(BlogPost blogpost)
//{
// if (ModelState.IsValid)
// {
// _repository.CreateBlogPost(blogpost);
// return RedirectToAction("Index");
// }
// return View(blogpost);
//}
[HttpPost]
public ActionResult Create(string zip, string make)
{
string url = "http://api.edmunds.com/v1/api/dealer?zipcode=" + zip.Replace(" ", "") + "&makeName=" + make.Replace(" ", "") + "&radius=3000&fmt=json&api_key=8rqtk3bb4bc4xgydqspvmc2s";
//WebRequest request = WebRequest.Create(url);
WebClient wc = new WebClient();
string stws = wc.DownloadString(url);
JToken root = JObject.Parse(stws);
JToken dealerholder = root["dealerHolder"];
DealerTentSaleMVC.Models.DealersTemp.DealerHolder convertedProducts = new DealerTentSaleMVC.Models.DealersTemp.DealerHolder();
string dh = dealerholder.ToString().Replace("[", "").Replace("]", "");
Result result = JsonConvert.DeserializeObject<Result>(stws);
foreach (var d in result.DealerHolder)
{
DealersTemp.DealerHolder newD = new DealersTemp.DealerHolder { active=d.active, contactinfo=d.contactinfo, address=d.address, id=d.id, locationId=d.locationId, logicalName=d.logicalName, make=d.make, name=d.name, operations=d.operations, publishDate=d.publishDate, syncPublishDate=d.syncPublishDate, type=d.type };
_repository.CreateDealer(d);
}
//DataContractJsonSerializer jsonSerializer =
// new DataContractJsonSerializer(typeof(DealersTemp.RootObject));
//DealersTemp.RootObject products = (DealersTemp.RootObject)jsonSerializer.ReadObject(ws.GetResponseStream());
//List<DealersTemp.DealerHolder> convertProducts = (DealersTemp.DealerHolder)products.dealerHolder;
return RedirectToAction("Index");
}
//
// GET: /Edmunds/Edit/5
public ActionResult Edit(int id)
{
DealersTemp.DealerHolder dealer = _repository.ReadDealer(id);
return View(dealer);
}
//
// POST: /Edmunds/Edit/5
[HttpPost]
public ActionResult Edit(DealerTentSaleMVC.Models.DealersTemp.DealerHolder dealerholder)
{
if (ModelState.IsValid)
{
_repository.UpdateDealer(dealerholder);
return RedirectToAction("Index");
}
return View(dealerholder);
}
//
// GET: /Edmunds/Delete/5
public ActionResult Delete(int id)
{
DealersTemp.DealerHolder dealer = _repository.ReadDealer(id);
return View(dealer);
}
//
// POST: /Edmunds/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
_repository.DeleteDealer(id);
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
}