Connecting to a Microsoft SQL Database from ASP.NET web service - c#

I have been trying to connect to a Microsoft SQL Server through a web service in visual studio 2015. However, I am having difficulty trying to retrieve data from the database.
In my web config file, I have the following code:
<add name="SecondlyReadingsContext" connectionString="Data Source=myserver;Initial Catalog=SecondlyReadingsContext;user=sa;password=adminadmin2" providerName="System.Data.SqlClient" />
I assume(might be wrong) that the code above establishes a connection with the server and the database itself. I referenced the above code from the following link:
Connecting to SQL server from Restful C# service
In my Model class, I have the following code:
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; }
}
}
In my Controller, I have this:
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;
}
}
}
I have also been told that I am supposed to do some kind of database connection in the following SecondlyReadingContext.cs file, but I am not sure of how to go about it:
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; }
}
}
When I run my server through IIS manager and add api/SecondlyReadings to the url, I am supposed to get the data back in json format, however, I am not retrieving any data and it returns a blank page(in a notepad, as I run it in Internet Explorer). Would anyone tell me what I have done wrong in my code, or anything that I have missed out. I have been working on this for a while and would really appreciate any help.
For reference, this is the dummy data that I added into the Microsoft SQL server which I am trying to retrieve:
My context file to after adding bindings:
Error after editing web.config file:
Updated result after editing web.config file

Set Initial Catalog to the name of your Database. Right now it's set to SecondlyReadingsContext, which I assume isn't the name of your Database.

Set your tables binding here to get data
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
public virtual DbSet<SecondlyReading> SecondlyReadings { get; set; }
Remember to re-name your table name on SQL Server End. to SecondlyReading

Related

Cant retrieve information from table in ASP.NET Entity Framework

Can't find why the object I'm supposed to retrieve from database is always empty, despite the fact that the table has 3 elements. In the view, Model.Count is always == 0. New to dotnet, stuck for hours.
What I did :
connection string in app.config
connection string in web.config
<connectionStrings>
<add name="masterEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DBModel" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1 .msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;initial catalog=core2DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
restart SQL Server
Controller seems to know about my tables since it autocomplete tables and keys.
Posts.cs
namespace WebApplication1.Data
{
public partial class Posts
{
public int Id { get; set; }
public Nullable<int> Post_owner { get; set; }
public string Post_content { get; set; }
public Nullable<int> Post_like_count { get; set; }
public virtual Users Users { get; set; }
}
}
Model1.Context.Cs:
namespace WebApplication1.Data
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class DBModel : DbContext
{
public DBModel() : base("DBModel")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* Database.SetInitializer<DBModel>(null);
base.OnModelCreating(modelBuilder);*/
}
public virtual DbSet<Posts> Posts { get; set; }
public virtual DbSet<Users> Users { get; set; }
}
}
In PostController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Diagnostics;
namespace WebApplication1.Controllers
{
public class PostController : Controller
{
// GET: Post
public ActionResult Index()
{
var context = new DBModel();
List<Posts> postsList = new List<Posts>();
if (!context.Posts.Any())
{
/* postsList = 3;*/
}
postsList = context.Posts.ToList();
/* using (var context = new DBModel())
{
postsList = context.Posts.ToList();
}*/
return View(postsList);
}
}
}
and the view is (Index.cshtml) :
#model List<WebApplication1.Data.Posts>
#{
ViewBag.Title = "Index";
}
<h2>Hello Peyo</h2>
<div>#Model</div>
#foreach (var post in Model)
{
<div><span>Nom: </span><span>#post.Post_content</span></div>
}
<span>Hello again</span>

How to put select query in a list in C#? I get an error

I'm trying to make a webpage in c# .net core razorpages. Basically I want the values of a specific column from my postgresql table in a list, and then show these values in the select option in html. But I'm having some problems on the c# side. I get this error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List<Project_Corona.Models.WorkspaceModel>' [Project_Corona]
Here is the code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Controllers
{
public class HomeController : Controller
{
public IActionResult Employeepage()
{
var cs = Database.Database.Connector();
using var con = new NpgsqlConnection(cs);
con.Open();
List<WorkspaceModel> res = new List<WorkspaceModel>();
res = ("Select location FROM workspaces").ToList();
return View();
}
}
}
This is the code from WorkspaceModel.cs (if necessary)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Models
{
public class WorkspaceModel
{
[BindProperty]
public string LocationName { get; set; }
[BindProperty]
public string RoomName { get; set; }
[BindProperty]
public int SquareMeters { get; set; } = 1;
[BindProperty]
public int Lengthws { get; set; } = 1;
[BindProperty]
public int Widthws { get; set; } = 1;
}
}
Have you tried to use EntityFramework Core for PostgreSQL to query your database?
I created a small example here
Simply create a DbContext with your database server settings:
public class WorkspaceContext : DbContext
{
public DbSet<WorkspaceModel> Workspaces { get; set; }
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase("inmemory");
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_pw");
}
... and call container.AddDbContext<WorkspaceContext>(); in your Dependency Injection configuration.
Now you can query your underlying database very easy by calling:
var res = ctx.Workspaces.Select(w => w.LocationName);
// var res = ctx.Workspaces.FromSqlRaw("Select location FROM workspaces");
Then you will get the result according to your sql statement: Select location FROM workspaces

How to display table from SQL Server using ASP NET MVC5 without using Entity Framework?

I'm kind of new ASP.NET MVC 5, but I already have working code in a controller to access database and can perform queries and stored procedure. But after searching Google for answers, I'm still lost on how to be able to retrieve data from my database and display it in a table format without using Entity Framework due to reasons from manager.
In simple words, I just want to do something as simple as select * from table and be able to display the data in a table format.
Here's what I have tried:
I tried to create a model class via ADO.NET and got the following 2 classes:
namespace AsyncFileProcessor.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class AsyncFileProcessingStatus : DbContext
{
public AsyncFileProcessingStatus()
: base("name=AsyncFileProcessingStatus")
{
}
public virtual DbSet<AsyncFileProcessingQueue> AsyncFileProcessingQueues { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
namespace AsyncFileProcessor.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("AsyncFileProcessingQueue")]
public partial class AsyncFileProcessingQueue
{
public int ID { get; set; }
[Required]
[StringLength(256)]
public string Filename { get; set; }
[StringLength(256)]
public string Path { get; set; }
public int Status { get; set; }
public DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
public DateTime UpdatedDate { get; set; }
public int UpdatedById { get; set; }
}
}
Then I manually created a controller:
namespace AsyncFileProcessor.Controllers
{
public class FileProcessStatusController : Controller
{
// GET: FileProcessStatus
public ActionResult Index()
{
return View();
}
}
}
For view, I just want the table to be displayed in Index.cshtml
#{
ViewBag.Title = "DynamicFileUploader";
}
//Stuff here....
<div class="col-lg-6">
<h1 style="text-align:center;">Placeholder</h1>
// The table would go inside this section
</div>
I tried #model IEnumerable<AsyncFile.....> in Index.cshtml, but it doesn't recognize anything related to my model.
Tried a lot of solutions online, but my lack of knowledge about MVC5 fails me.
If someone can help me figure out how I can accomplish this and maybe explain the whole MVC5 workflow in simple terms, I would appreciate it.
I can do this easily in Django :(
You can use Dapper ORM developed by StackExchange.
It basically maps an object-oriented domain model to a traditional relational database. Otherwise, you will have to use ADO.Net.
For example,
public async Task<IList<AsyncFileProcessingQueue>> GetAsyncFileProcessingQueue()
{
IList<AsyncFileProcessingQueue> result;
using (IDbConnection conn = new SqlConnection(DataConnectionString))
{
conn.Open();
var entities = await conn.QueryAsync<AsyncFileProcessingQueue>
("SELECT * FROM YOUR_TABLE");
result = entities.ToList();
}
return result;
}
Dapper is lightweight and very fast. I use it, if I do not have control over Database or Database is not normalized.
If you want to write less SQL, but still have Dapper-like performance, you can use Tortuga Chain.
using Tortuga.Chain;
static SqlServerDataSource s_Data = new SqlServerDataSource(DataConnectionString);
public async Task<IList<AsyncFileProcessingQueue>> GetAsyncFileProcessingQueue()
{
return s_Data.From("YOUR_TABLE").ToCollection<AsyncFileProcessingQueue>().ExecuteAsync();
}
https://github.com/docevaad/Chain/wiki/A-Chain-comparison-to-Dapper

Error 1 Error 2 on Conference MVC Tutorial

Hi there im following the series of MVC tutorials given by microsoft and i came across this problem:
Error 1 The best overloaded method match for
'System.Data.Entity.DbSet.Add(Conference.Models.Session)'
has some invalid arguments visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 18 31 Conference
Error 2 Argument 1: cannot convert from 'Conference.Models.Speaker' to
'Conference.Models.Session' visual studio
2013\Projects\Conference\Conference\Models\ConferenceContextInitializer.cs 19 34 Conference
ConferenceModelInitializer
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
{
protected override void Seed(ConferenceContext context)
{
context.Sessions.Add(
new Session()
{
Title = "I Want Spaghetti",
Abstract = "The Life and times of a spaghetti lover",
Speaker = context.Speakers.Add(
new Speaker()
{
Name = "Jon Pepe",
EmailAddress = "jon#asfdasd.com"
})
});
context.SaveChanges();
}
}
}
ConferenceContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Conference.Models
{
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
}
Thank you!
replace:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Session> Speakers { get; set; }
}
with:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Speaker> Speakers { get; set; } //since you are referencing the speaker class here
}

Add View - Cannot retrieve Metadata

I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.
Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities
The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.
There was an error running the selected code generator: 'Unable to
retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'
My controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class MoviesController : Controller
{
private MoviesEntities db = new MoviesEntities();
// GET: /Movies/
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ActionResult EmployeeInfo()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };
return View(query.Distinct().ToList());
}
}
}
My context
//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------
namespace WebApplication2.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using movieLayer;
using WebApplication2.Models;
public partial class MoviesEntities : DbContext
{
public MoviesEntities()
: base("name=MoviesEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Location> Locations { get; set; }
public virtual DbSet<Movie> Movies { get; set; }
public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Show> Shows { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
}
}
Model of EmployeeInfo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication2.Models
{
public class EmployeeInfo
{
public EmployeeInfo() { }
public string Name { get; set; }
public string Role { get; set; }
public DateTime Birthday { get; set; }
}
}
What I did to solve this issue that I encountered when adding a scaffolded view by right clicking the controller action was to leave the "Data context class" field blank.
I'm not entirely sure as to why this works but I found this method from ASP.NET forums.
Make sure you rebuild your solution first. If you just added a new class, the scaffolding engine may not actually know about it, yet, if the project hasn't compiled.
If that doesn't work, close Visual Studio and restart. I have seen the scaffolding stuff just go wonky for no good reason in VS2012, and a restart will usually fix it.
The problem was the EmployeeInformation was just a "template" for the controller to dump it's data into from the query for the View.
EmployeeInformation was not actually an existing table, thus I had to make a model i.e. EmpleeInfoModels to hold the data, that was then passed to my custom View.
Method
public ActionResult EmployeeInformation()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfoModels() { Name = e.Name, RoleType = r.RoleType, Birthdate = e.Birthday, eID = e.ID };
return View(query.Distinct().ToList().Distinct());
}
Model
namespace WebApplication2.Models
{
public class EmployeeInfoModels
{
public int mID { get; set; }
public int eID { get; set; }
public string Name { get; set; }
public string RoleType { get; set; }
public DateTime Birthdate { get; set; }
}
}
And my View just brought in
#model IEnumerable<WebApplication2.Models.EmployeeInfoModels>
Adding one more tip: you may have this error if you have any configSource attributes in any of the elements in your web.config. I commented out all of the elements that contained a configSource attribute and then ran the scaffolding again and it worked like a charm. Once it was finished, I uncommented the elements in the web.config and I was all set.
Check your DataContextClass Option in Add View Pop winow and then correct the ConnectionString when adding your View from Controller
Refer Screenshot
.

Categories