Repository in MVC - asp.net-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/

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

When I add new record to the Entity,it gives DbUpdateException

// Here is the controller that reads a file uploaded.It works successfully when file is uploaded to App_Data,but when uploaded to MS SQL Server it gives error as "Invalid Object dbo.Prescription"
using SastiDawaai.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
namespace SastiDawaai.Controllers
{
public class MedicineController : Controller
{
// GET: Medicine
public ActionResult Index()
{
MedicineContext medctx = null;
using(medctx=new MedicineContext())
{
List<Medicine> medicinelist=medctx.Medicines.ToList();
return View(medicinelist);
}
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
MedicineContext medctx = null;
Prescription pres = null;
if(file!=null && file.ContentLength>0)
{
////upolading files to App_Server
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), filename);
file.SaveAs(path);
//uploading Files to database
var file_content=new BinaryReader(file.InputStream);
var content=file_content.ReadBytes(file.ContentLength);
using (medctx = new MedicineContext())
{
pres = new Prescription
{
Prescription_Receipt = content,
File_Name = filename,
Submitted_Date = DateTime.Now,
};
medctx.Prescriptions.Add(pres);
medctx.SaveChanges();
}
}
return RedirectToAction("Index");
}
}
}
//Here is the Model for Prescription
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace SastiDawaai.Models
{
public class Prescription
{
[Key]
public int Prescription_Id { get; set; }
public byte[] Prescription_Receipt { get; set; }
public DateTime Submitted_Date { get; set; }
public string File_Name { get; set; }
}
}
//here is the DBContext Class having 2 DBSets "Medicine" and "Prescription"
//There is no issue in getting records and inserting Records in Medicine entity,the issue only occurs when adding record to any additional DBSet added to the context.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SastiDawaai.Models
{
public class MedicineContext:DbContext
{
public virtual DbSet<Medicine> Medicines { get; set; }
public virtual DbSet<Prescription> Prescriptions { get; set; }
}
}
Check you Table name in your database
you entity is Prescription and your table name should be PrescriptionS,and also check you table schema, in your Entity it's Dbo so your table in your database should be the same schema.

unable to retrieve metadata for my model class when i want to accesse model data from controller

I am trying to make an application where in I have made a Location model,controller and views using scaffolding. I have location name and location ID properties in location. Database is getting created and location table also and data is getting populated. Now i want to make a department class where I have 3 properties namely Dept_ID, Dept_Name and Loc_ID(Foreign key). I have added required codes in respective files as following.
in Department.cs(Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DMS.Models
{
public class Department
{
public int D_ID { get; set; }
public string D_Name { get; set; }
[ForeignKey("L_ID")]
public int L_ID { get; set; }
}
}
in DB_CONTEXT class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace DMS.Models
{
public class DB_CONTEXT : DbContext
{
public DbSet<Location> Movies { get; set; }
public DbSet<Department> Department { get; set; }
}
}
and in locatoin.cs(Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DMS.Models
{
public class Location
{
public int ID { get; set; }
public string L_Name { get; set; }
}
}
when i am trying to add a controller for Department I am getting an error as
unable to retrieve metadata for 'DMS.Models.Department' The navigation property 'L_ID' is not declared property on type Department.Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
[ForeignKey("LoactionID")]
public int L_ID { get; set; }
public Virtual Location Location {get;set;}
Make these changes in Department model and try once again. I hope this will solve your issue.

Resources