Populate a model from database ASP.NET MVC - 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

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);

MVC 5 Retrieving Data from SQL Server

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 :-)

Latest News, The ObjectContext instance has been disposed

I am trying to get the Latest News from my database but I keep getting this error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. the error happens on the NewsEntity.GetObject() method. I've tried adding the ToList, enabled LazyLoading, re-ordered the way I create the object sets. I have taken out the loading of the Author and Icon and that worked but I need them :) Thanks for any help.
Here is my NewsEntity class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Web.Repository.Entity
{
public class NewsEntity : BaseEntity<News>
{
public int Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Content { get; set; }
public int Icon { get; set; }
public DateTime Posted { get; set; }
public int Author { get; set; }
public bool Deleted { get; set; }
public virtual MemberEntity AuthorEntity { get; set; }
public virtual IconEntity IconEntity { get; set; }
public override News GetObject()
{
return new News
{
Id = Id,
Title = Title,
Summary = Summary,
Content = Content,
IconId = Icon,
Icon = IconEntity.GetObject(),
Posted = Posted,
AuthorId = Author,
Author = AuthorEntity.GetObject(),
Deleted = Deleted
};
}
}
}
This is my NewsObject class (For data transfer):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Web.Repository.Entity
{
public class News : BaseObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Content { get; set; }
public int IconId { get; set; }
public DateTime Posted { get; set; }
public int AuthorId { get; set; }
public bool Deleted { get; set; }
public Member Author { get; set; }
public Icon Icon { get; set; }
}
}
This is my Database Context class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using Web.Repository.Entity;
namespace Web.Repository
{
public class WebModelContext : ObjectContext
{
private IObjectSet<MemberEntity> _members;
private IObjectSet<IconEntity> _icons;
private IObjectSet<NewsEntity> _news;
public WebModelContext()
: base("name=WebRepository", "WebRepository")
{
ContextOptions.LazyLoadingEnabled = true;
_members = CreateObjectSet<MemberEntity>();
_icons = CreateObjectSet<IconEntity>();
_news = CreateObjectSet<NewsEntity>();
}
public IObjectSet<MemberEntity> Members
{
get { return _members; }
}
public IObjectSet<IconEntity> Icons
{
get { return _icons; }
}
public IObjectSet<NewsEntity> News
{
get { return _news; }
}
}
}
This is my NewsRepository class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.Repository.Entity;
namespace Web.Repository
{
public class NewsRepository : IDisposable
{
private WebModelContext _context;
private WebModelContext Context
{
get
{
if (_context == null)
_context = new WebModelContext();
return _context;
}
}
public NewsRepository() { }
public IEnumerable<News> GetLatestNews()
{
return Context.News.Where(news => !news.Deleted).OrderByDescending(news => news.Posted).Take(5).ToList().Select(news => news.GetObject());
}
#region Disposing
private bool disposed;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing && _context != null)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
This is my class to get the latest news:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Repository.Entity;
using Web.Repository;
namespace Web.Infrastructure
{
public static class NewsHelper
{
public static IEnumerable<News> GetLatestNews()
{
IEnumerable<News> news;
using (var repository = new NewsRepository())
{
news = repository.GetLatestNews();
}
return news;
}
}
}
This is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Repository.Entity;
using Web.Models;
using Web.Infrastructure;
namespace Web.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index()
{
NewsListModel model = new NewsListModel { News = NewsHelper.GetLatestNews().ToList() };
return View(model);
}
}
}
and finally this is my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Repository.Entity;
namespace Web.Models
{
public class NewsListModel
{
public IEnumerable<News> News { get; set; }
}
}
I fixed this by ensuring the latest news was infact a list instead of a collection/iqueryable

Controller class not available in Add View ASP.NET MVC

I have created the following controller i want to add view that should have the data access class UserMagnament.Controller.menuitems but when i add view by right clicking on view folder,it is not showing "UserMagnament.Controller.menuitems" in add data class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManagement.Models;
namespace UserManagement.Controllers
{
public class menuitems
{
EvoLetDataContext db1 = new EvoLetDataContext();
public menuitems()
{ }
public IQueryable<UMUserType> menuitems()
{
return db1.UMUserTypes;
//this.Packages = _SysPackage;
//this.Modules = _SysModule;
}
public List<SysPackage> Packages { get; private set; }
public List<SysModule> Modules { get; private set; }
}
public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View(new menuitems());
}
}
}
Did you rebuild your mvc application? Sometimes it helps to populate the class list when adding a View.

Resources