MVC 5 Retrieving Data from SQL Server - asp.net-mvc

Could somebody please explain how I retrieve a simple set of records from a SQL Server 2012 database to display on an ASP.NET page? I have tried following some tutorials but I am missing something and I cant see the wood for the trees.
I have a connection string in the web.config file:
<add name="DefaultConnection"
connectionString="Data Source=MY-LAPTOP;Initial Catalog=Test;Integrated Security=True"
providerName="System.Data.SqlClient" />
I have a class called Navigation.cs which is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public partial class Navigation
{
public int navigation_ID { get; set; }
public string title_TV { get; set; }
public Nullable<int> position_IV { get; set; }
public bool main_BT { get; set; }
public string url_TV { get; set; }
}
}
I have a Shared/_layout.cshtml page which has the following code:
#model List<WebApplication1.Models.Navigation>
#foreach (var item in Model) {
<li>#Html.DisplayFor(modelItem => item.title_TV)</li>
}
I also have a controller called HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
I get the following error
An exception of type 'System.NullReferenceException' occurred in App_Web_wqu1n0vj.dll but was not handled in user code.
I have created a class called TestEntities.cs which is as follows:
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace WebApplication1.Models
{
public partial class TestEntities : DbContext
{
public TestEntities()
: base("name=DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Navigation> Navigations { get; set; }
}
}
Any help would be much appreciated :-)

Related

ASP.NET MVC add-migration. Project failed to build

I am trying to enable migrations for data entity: In Package Manager Console:
Enable-Migrations -ProjectName Vidly -ContextTypeName Vidly.Models.MyDBContext
I get:
Code First Migrations enabled for project Vidly.
Then
add-migration 'InitialModel'
I get: "The project 'Vidly' failed to build."
My Configuration.cs:
namespace Vidly.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Vidly.Models.MyDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Vidly.Models.MyDBContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
And my MyDBContext.cs is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Vidly.Models
{
public class MyDBContext
{
public DbSet<Customer> Customers { get; set; } // My domain models
public DbSet<Movie> Movies { get; set; }// My domain models
}
}
The error message is:
error CS0311: The type 'Vidly.Models.MyDBContext' cannot be used as
type parameter 'TContext' in the generic type or method
'DbMigrationsConfiguration'. There is no implicit reference
conversion from 'Vidly.Models.MyDBContext' to
'System.Data.Entity.DbContext'.
It seems I cannot use MyDBContext as a type super class in Configuration.cs.
Please help. Thanks.
You are missing to implement DbContext.
Change AND try:
public class MyDBContext:DBContext
{
public MyDBContext() : base("ConnectionStringName")
{
}
public DbSet<Customer> Customers { get; set; } // My domain models
public DbSet<Movie> Movies { get; set; }// My domain models
}
Couple of things you are missing here.
Inheriting from DBContext
Constructor to pass the name of connection string entry you used in
use below snippet of code. note: replace VidlyDBConnectionString with your connection string name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Vidly.Models
{
public class MyDBContext :DbContext
{
public MyDBContext():base("name=VidlyDBConnectionString")
{
}
public DbSet<Customer> Customers { get; set; } // My domain models
public DbSet<Movie> Movies { get; set; }// My domain models
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Vidly.Models;
{
public class MyDBContext :DbContext
{
public DbSet<Customer> Customers { get; set; } // My domain models
public DbSet<Movie> Movies { get; set; } // My domain models
}
}

Asp MVC core 2.0 automapper ('Missing type map configuration or unsupported mapping.')

I created the new asp mvc core 2.0 angular template and added models and dtos which I want to map in the controller with Automapper. I included automapper 6.1.1 . When I navigate to http://localhost:61031/api/classes it gives me the exception Missing type map configuration or unsupported mapping. I read through many posts but are unable to find what is going on.
My code is as follows:
Overview of project
MODELS
Models.Classes.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Classes
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string ClassName { get; set; }
[Required]
[Range(1, 50)]
public int MaxStudents { get; set; }
public ICollection<Students> Students { get; set; } = new List<Students>();
}
}
Models.Students.cs
using System;
namespace WebApplication1.Models
{
public class Students
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Gender Gender { get; set; }
public Classes Classes { get; set; }
public int ClassId { get; set; }
}
}
Models.EdulyContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class EdulyContext : DbContext
{
public EdulyContext(DbContextOptions<EdulyContext> options) : base(options)
{
Database.Migrate();
}
public DbSet<Classes> Classes { get; set; }
public DbSet<Students> Students { get; set; }
}
}
DTOS
Dto.ClassesDtos.ClassesDto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
namespace WebApplication1.Dto.ClassesDtos
{
public class ClassesDto
{
public string ClassName { get; set; }
public int MaxStudents { get; set; }
public ICollection<Students> Students { get; set; } = new List<Students>();
}
}
Dto.StudentsDtos.StudentDto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
namespace WebApplication1.Dto.StudentsDtos
{
public class StudentsDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Gender Gender { get; set; }
public Models.Classes Classes { get; set; }
public int ClassId { get; set; }
}
}
CONTROLLERS
Controllers.ClassesController.cs
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Dto.ClassesDtos;
using WebApplication1.Repositories.Interfaces;
namespace WebApplication1.Controllers
{
[Route("api/classes")]
public class ClassesController : Controller
{
private IClassesRepository _classesRepository;
public ClassesController(IClassesRepository classesRepository)
{
_classesRepository = classesRepository;
}
[HttpGet()]
public IActionResult GetClasses()
{
var classesEntities = _classesRepository.GetClasses();
var results = Mapper.Map<ClassesDto>(classesEntities);
return Ok(results);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
host.Run();
}
public static IWebHost BuildWebHost(string[] args)
{
return new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((builderContext, config) =>
{
IHostingEnvironment env = builderContext.HostingEnvironment;
})
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Models;
using WebApplication1.Dto;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Repositories.Interfaces;
using WebApplication1.Repositories;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connectionString = #"server=(localdb)\mssqllocaldb;Database=EdulyDbCore2;Trusted_Connection=True";
services.AddDbContext<EdulyContext>(o => o.UseSqlServer(connectionString));
services.AddScoped<IClassesRepository, ClassesRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Models.Classes, Dto.ClassesDtos.ClassesDto>();
cfg.CreateMap<Dto.ClassesDtos.ClassesDto, Models.Classes>();
cfg.CreateMap<Models.Students, Dto.StudentsDtos.StudentsDto>();
cfg.CreateMap<Dto.StudentsDtos.StudentsDto, Models.Students>();
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
In the startup I mapped both directions from classes to classesDto just to be certain. If anyone has any idea what I am doing wrong, help would be much aprreciated. Cheers!
After taking a small break I suddenly realized my mistake.
In classes controller the get return type should be an IEnumerable
so:
var results = Mapper.Map(classesEntities);
should become:
var results = Mapper.Map>(classesEntities);

Populate a model from database ASP.NET MVC

I have the following model:
namespace Factura.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("factura.marfa")]
public partial class marfa
{
[Key]
public int idmarfa { get; set; }
[StringLength(45)]
public string denumire { get; set; }
public int idfurnizor { get; set; }
}
}
And I have also a class that inherits DbContext:
namespace Factura.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class FacturaContext : DbContext
{
public FacturaContext() : base("name=FacturaContext")
{
}
public virtual DbSet<marfa> marfas { get; set; }
[...]
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
[...]
}
}
}
In my controller I have the following code:
namespace Factura.Controllers
{
[Authorize]
public class CumparatorController : Controller
{
FacturaContext dbFactura = new FacturaContext();
[HttpGet]
public ActionResult Cumparaturi()
{
var marfas = dbFactura.marfas.ToList();
return View(marfas);
}
}
}
The problem I have is that dbFactura.marfas is null, it doesn't bring anything from Database even if the table is populated.
Can anyone help me with this?
Thank you!
Remove [Table("factura.marfa")] from marfa class and add the following in your OnModelCreating in FacturaContext
modelBuilder.Entity<marfa>().ToTable("factura_marfa"); //updated . with _
Create the migration & run

Repository in MVC

I have a dbml file that has stored procedures dragged off. I have an EmployeeModel class that has get and set properties.
I have an interface IEmployee and an EmployeeRepository repository that has the implementation of the methods. Please refer to the code. In the stored procedure GetRoles I just have SELECT * FROM ROLE.
In the repository, how do I loop through the resultset? Can I change ISingleResult to IMultipleResult in the dbml designer file?
EmployeeModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcWebsite.Models
{
public class EmployeeModel
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public string TaskMark { get; set; }
public int RoleFlag { get; set; }
}
}
IEmployee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcWebsite.Models;
namespace MvcWebsite.DAL
{
public interface IEmployees
{
IList<EmployeeModel> ListAll();
// void Save(EmployeeModel employ);
}
}
EmployeeRepository.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcWebsite.Models;
using System.Data.Linq;
namespace MvcWebsite.DAL
{
public class EmployeeRepository:IEmployees
{
private DataDataContext _dataContext;
public EmployeeRepository()
{
_dataContext = new DataDataContext();
}
public IList<EmployeeModel> ListAll()
{
//IMultipleResults result =_dataContext.GetRoleDetails();
//var Emps = result.GetResult(EmployeeModel);
List<EmployeeModel> emp = _dataContext.GetRoleDetails();
// foreach (GetRoleDetailsResult role in Emps)
// {
// role.Description=Emps.
// }
return Emps.ToList();
}
}
}
Error:
Error 1 Cannot implicitly convert type
'System.Collections.Generic.List'
to
'System.Collections.Generic.IList'.
An explicit conversion exists (are you missing a
cast?) C:\Users\guhananth\documents\visual studio
2010\Projects\MVC_SP\MvcWebsite\DAL\EmployeeRepository.cs 44 19 MvcWebsite
Typicall you would use:
List<EmployeeModel> emp = _dataContext.Employees.ToList();
You can read about a Entity Framework implementation of the Repository pattern here: http://blog.gauffin.org/2013/01/repository-pattern-done-right/

Creating MVC application using Razor Engine and EF CodeFirst

I am practicing Entity Framework. I am practicing Asp.net MVC framework using Razor Engine and EF Code First. In practicing it, I found to have few problems. The problem is the Entity Framework doesnt creates a database in my SQL.
I am using VisualStudio 2011 Beta Version with MSSQL 2008. I dont know what the problem is.
Help required. Below is my Code :
Person.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace MvcDemo.Data
{
public class Person
{
[Key]
public int PersonID { get; set; }
[Required]
[StringLength(40)]
public string FirstName { get; set; }
[Required]
[StringLength(30)]
public int LastName { get; set; }
public int? Age { get; set; }
[ForeignKey("PrefixID")]
public Prefix Prefix { get; set; }
[Required]
public int PrefixID { get; set; }
}
}
Prefix.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace MvcDemo.Data
{
public class Prefix
{
public int PrefixID { get; set; }
[Required]
[StringLength(20)]
public string PrefixName { get; set; }
}
}
MvcContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using MvcDemo.Data;
namespace MvcDemo.DataAccess
{
public class MvcContext : DbContext
{
public MvcContext()
: base("name = MvcDemoApp")
{
}
public DbSet<Person> People { get; set; }
public DbSet<MvcDemo.Data.Prefix> Prefix { get; set; }
}
}
ConnectionString:
<connectionStrings>
<add name="MvcDemoApp"
connectionString="Server=.;Initial Catalog=MvcDemoApp;Integrated Security=true"
providerName="System.Data.SqlClient" />
If this is all of your code it is not surprising that a database is not created. There is no code that executes commands against the database. As soon as you start iterating over e.g. MvcContext.People or do some insert you will notice that the database gets created.
There are plenty step-by-step examples online. I would pick one of them and do a walk through; you can try this one for example: http://msdn.microsoft.com/en-us/data/gg685467.aspx. It should cover most of the basics to get you started.
If you prefer video over text, search Channel 9, or pluralsight
You should operate package manager console to do it.
Ope package manager console window and run "update-database" command, there still a bug in this command so you need to specify "startupprojectname" param to execute it and connection string in you DbContext file.

Resources