【问题标题】:Connecting to a Microsoft SQL Database from ASP.NET web service从 ASP.NET Web 服务连接到 Microsoft SQL 数据库
【发布时间】:2017-08-11 06:15:30
【问题描述】:

我一直在尝试通过 Visual Studio 2015 中的 Web 服务连接到 Microsoft SQL Server。但是,我在尝试从数据库中检索数据时遇到了困难。

在我的网络配置文件中,我有以下代码:

<add name="SecondlyReadingsContext" connectionString="Data Source=myserver;Initial Catalog=SecondlyReadingsContext;user=sa;password=adminadmin2" providerName="System.Data.SqlClient" />

我假设(可能是错误的)上面的代码建立了与服务器和数据库本身的连接。我从以下链接引用了上面的代码: Connecting to SQL server from Restful C# service

在我的模型类中,我有以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace HelloWorld.Models.APiModels
{
    public class SecondlyReading
    {

        [Key]
        public int Id { get; set; }
        [Required]
        public int ChannelID { get; set; }
        [Required]
        public string TimeStamp { get; set; }
        [Required]
        public float RMSVoltage { get; set; }
        [Required]
        public float Frequency { get; set; }
        [Required]
        public float RMSCurrent { get; set; }
        [Required]
        public float RealPower { get; set; }
        [Required]
        public float ReactivePower { get; set; }
        [Required]
        public float ApparentPower { get; set; }
        [Required]
        public float PowerFactor { get; set; }
        [Required]
        public string DeviceId { get; set; }

        //[ForeignKey("DeviceId")]
        //public virtual Device Device { get; set; }

    }
}

在我的控制器中,我有这个:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using HelloWorld.Models;
using HelloWorld.Models.APiModels;

namespace HelloWorld.Controllers
{
    public class SecondlyReadingsController : ApiController
    {
        private SecondlyReadingsContext db = new SecondlyReadingsContext();

        // GET: api/SecondlyReadings
        public IQueryable<SecondlyReading> GetSecondlyReadings()
        {
            return db.SecondlyReadings;
        }

        // GET: api/SecondlyReadings/5
        [ResponseType(typeof(SecondlyReading))]
        public IHttpActionResult GetSecondlyReading(int id)
        {
            SecondlyReading secondlyReading = db.SecondlyReadings.Find(id);
            if (secondlyReading == null)
            {
                return NotFound();
            }

            return Ok(secondlyReading);
        }

        // PUT: api/SecondlyReadings/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutSecondlyReading(int id, SecondlyReading secondlyReading)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != secondlyReading.Id)
            {
                return BadRequest();
            }

            db.Entry(secondlyReading).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SecondlyReadingExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/SecondlyReadings
        [ResponseType(typeof(SecondlyReading))]
        public IHttpActionResult PostSecondlyReading(SecondlyReading secondlyReading)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.SecondlyReadings.Add(secondlyReading);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = secondlyReading.Id }, secondlyReading);
        }

        // DELETE: api/SecondlyReadings/5
        [ResponseType(typeof(SecondlyReading))]
        public IHttpActionResult DeleteSecondlyReading(int id)
        {
            SecondlyReading secondlyReading = db.SecondlyReadings.Find(id);
            if (secondlyReading == null)
            {
                return NotFound();
            }

            db.SecondlyReadings.Remove(secondlyReading);
            db.SaveChanges();

            return Ok(secondlyReading);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool SecondlyReadingExists(int id)
        {
            return db.SecondlyReadings.Count(e => e.Id == id) > 0;
        }
    }
}

我还被告知我应该在下面的 SecondReadingContext.cs 文件中进行某种数据库连接,但我不确定如何去做:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace HelloWorld.Models
{
    public class SecondlyReadingsContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, please use data migrations.
        // For more information refer to the documentation:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx

        public SecondlyReadingsContext() : base("name=SecondlyReadingsContext")
        {   

        }

        public System.Data.Entity.DbSet<HelloWorld.Models.APiModels.SecondlyReading> SecondlyReadings { get; set; }
    }
}

当我通过 IIS 管理器运行我的服务器并将 api/SecondlyReadings 添加到 url 时,我应该以 json 格式取回数据,但是,我没有检索任何数据并且它返回一个空白页(在记事本中,因为我在 Internet Explorer 中运行它)。谁能告诉我我的代码做错了什么,或者我错过了什么。我已经为此工作了一段时间,非常感谢任何帮助。

作为参考,这是我添加到我试图检索的 Microsoft SQL 服务器中的虚拟数据:

添加绑定后我的上下文文件:

编辑 web.config 文件后出错:

编辑 web.config 文件后更新结果

【问题讨论】:

  • SecondlyReadingsContext您的型号名称吗?
  • 为什么选择 api/Readings?看起来它需要 api/SecondlyReadings
  • 你有什么错误吗?
  • 第二个是读数,只是编辑过的。对不起@DavidN 的困惑
  • 你需要修改你的连接字符串。对于模型,它还包含更多细节。

标签: c# sql-server database web-services database-connection


【解决方案1】:

将初始目录设置为您的数据库的名称。现在它设置为 SecondReadingsContext,我认为这不是您的数据库的名称。

【讨论】:

  • 虽然我已经更改了它,但仍然无法获取任何数据。我需要在上下文文件中添加任何内容吗?
  • 您能显示名称或您的数据库以及您设置的内容吗?
  • 您在主机 myserver 上有一个名为 cloudsql 的数据库吗?
  • 更改了数据库名称
【解决方案2】:

在此处设置您的表绑定以获取数据

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

}
public virtual DbSet<SecondlyReading> SecondlyReadings { get; set; } 

记得在 SQL Server End 上重命名您的表名。到SecondReading

【讨论】:

  • 看起来他是在使用Entity Framework Code First,所以SqlClient是对的。
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多