An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user codeASP.NET WebAPI錯誤:在EntityFramework.dll中發生類型'System.Data.SqlClient.SqlException'的異常,但未在用戶代碼中處理
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
每當我調用任何函數I'已經寫在控制器中。
所述控制器(網絡API 2控制器空):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Test.DBA;
using Test.Models;
namespace Test.Controllers
{
public class UserAPIController : ApiController
{
ApiDbContext dbContext = null;
public UserAPIController()
{
dbContext = new ApiDbContext();
}
[HttpPost]
public IHttpActionResult InsertUser(User user)
{
dbContext.Users.Add(user);
dbContext.SaveChangesAsync();
return Ok(user.Id);
}
public IEnumerable<User> GetAllUser()
{
var list = dbContext.Users.ToList();
return list;
}
[HttpPost]
public IHttpActionResult DeleteUser(User user)
{
dbContext.Users.Remove(user);
dbContext.SaveChangesAsync();
return Ok(user.Id);
}
[HttpGet]
public IHttpActionResult ViewUser(int id)
{
var student = dbContext.Users.Find(id);
return Ok(student);
}
[HttpGet]
public IHttpActionResult UpdateUser(User user)
{
var std = dbContext.Users.Find(user.Id);
std.Name = user.Name;
//std.startTime = user.startTime;
//std.endTime = user.endTime;
//std.Gender = user.Gender;
//std.Adress = user.Adress;
dbContext.Entry(std).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChangesAsync();
return Ok();
}
}
}
模型類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
//public DateTime startTime { get; set; }
//public DateTime endTime { get; set; }
//public string Gender { get; set; }
//public string Adress { get; set; }
}
}
編輯:連接字符串代碼加入
<connectionStrings>
<add name ="Connection"
connectionString="Data Source=\.SQLEXPRESS;Initial Catalog=PonesiLoptu;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>*
編輯2:ApiDbContext代碼添加。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Test.Models;
namespace Test.DBA
{
public class ApiDbContext :DbContext
{
public ApiDbContext() : base("Connection")
{
}
public DbSet<User> Users { get; set; }
}
}
請向我們展示'ApiDbContext',可能是連接字符串名稱問題或錯誤的連接字符串,您可以連接到數據庫嗎? – Ofiris
@Ofiris我加了。 – Saizaku
你可以試試localhost \ sqlexpress? – Ofiris