我正在使用 Breeze WebAPI 将新行保存到我的数据库中,但是当我尝试调用方法 SaveChanges() 时,我收到错误 Invalid object name 'dbo.tblAgencyQuery。
请参阅下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Breeze.WebApi;
using AgencyUpdate.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AgencyUpdate.Controllers
{
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<AgencyDbContext> _ContextProvider =
new EFContextProvider<AgencyDbContext>();
[HttpGet]
public string MetaData()
{
return _ContextProvider.Metadata();
}
[HttpGet]
public IQueryable<api_Agency> GetAgency()
{
return _ContextProvider.Context.api_Agency;
}
[HttpPost]
public void SaveData(JObject data)
{
Newtonsoft.Json.Linq.JToken[] agency = data.GetValue("agency").ToArray();
dynamic DeserializedData = JsonConvert.DeserializeObject(agency[0].ToString());
//using (var context = new AgencyDbContext())
//{
// tblAgencyQuery AgencyQuery = new tblAgencyQuery(); {
// AgencyQuery.QueryID = Guid.NewGuid();
// AgencyQuery.QueryText = agency[0].ToString();
// AgencyQuery.AgencyID = DeserializedData.agencyID;
// };
// context.tblAgencyQuery.Add(AgencyQuery);
// context.SaveChanges();
//}
tblAgencyQuery tblAgencyQuery = new tblAgencyQuery();
tblAgencyQuery.QueryID = Guid.NewGuid();
tblAgencyQuery.QueryText = agency[0].ToString();
tblAgencyQuery.AgencyID = DeserializedData.agencyID;
_ContextProvider.Context.tblAgencyQuery.Add(tblAgencyQuery);
_ContextProvider.Context.Entry(tblAgencyQuery).State = System.Data.EntityState.Added;
_ContextProvider.Context.SaveChanges();
}
[HttpGet]
public IQueryable<api_AgencyOffice> GetOffice()
{
return _ContextProvider.Context.api_AgencyOffice;
}
[HttpGet]
public IQueryable<api_AgencyContact> GetContact()
{
return _ContextProvider.Context.api_AgencyContact;
}
}
}
我从我的 javascript调用public void SaveData(JObject data) 。我反序列化数据并将值分配给 tblAgencyQuery 的新实例。然后我将它添加到上下文中,以便我准备好保存数据。
但是 SavedChanges() 不喜欢我的对象。它期待一个不同的对象吗?
这是异常窗口
我的 JavaScript 方法
var saveChanges = function (agencyObservable) {
if (agencyObservable) {
var data = ko.toJSON(agencyObservable);
var options = {
url: '/breeze/SaveData',
type: 'POST',
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8"
}
return $.ajax(options)
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
log('Saved data successfully', saveResult, true);
};
function saveFailed(error) {
var msg = 'Save failed: ' + error.message;
logger.log(msg, error, system.getModuleId(datacontext), true);
error.message = msg;
}
}
};