ASP.NET MVC add-migration. Project failed to build - asp.net-mvc

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
}
}

Related

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

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

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/

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.

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