EntityException in MVC4 - asp.net-mvc

I am new to MVC and i am having a problem. I have one table named tblEmployee , model Employee. Controller EmployeeController. i am having EntityException in my EmployeeController controller.
My code for Model:
namespace MvcPractice.Models
{
[Table("tblEmployee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
}
i have created EmployeeContext.cs in Model:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MvcPractice.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Connection string:
<connectionStrings>
<add name="EmployeeContext"
connectionString="server=.;database=MvcDemo; integrated security=SSPI;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

This is a web application but you are using integrated security to connect. That will use the identity of your web application. It's preferable to use a real SQL Server user created for your application. So create a user and change your connection string to something like this:
server=.;database=MvcDemo;User ID=<username>;Password=<password>;
Additionally, it's unusual for a local installation of SQL Server to be installed with an empty instance name, so you may also need to check that the server name shouldn't be this, just check what your SQL Server Management Studio is using to connect:
.\sqlexpress

Related

How to Connect Model with Controller and View Using Razor Entity Frame work (CRUD) using Mac OS edition of Visual Studio 2022

I'm very much begginer to ASP.net and Just followed a tutorial and created a small web app.I understood the basics up to creating a Model in Visual Studio Mac Edition (2022) , However , when I tried to use entity frame work to Link controller and create a view with user interface ,I get null value for "DB context Class to Use" field. I don't know how to fix this issue since I'm using Mac edition of Visual Studio. DB connect Class to Use is Null
Following is my code in the Model class
using System;
using System.Linq;
using System.Data;
namespace WiseTaskMgtSystem.Models
{
public class UserModel
{
public int ID { get; set; }
public String UserName { get; set; }
public String password { get; set; }
public UserModel()
{
}
}
}
Model Class
I would be highly appreciated if someone could assist me on this to solve the issue.
Thank you.!
did you add DBcontextin your solution ? take Image from solution explorer
DbContext is base class for managing database connections and provides functionality for CRUD operations, that is Database related functionality like data access methods to interact with Database.
In Example below UserProfile is Table in the Database.
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
// Class UserProfile maps to the Database Table [UserProfile]
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}

How do you resolve an MVC namespace compile error after renaming model?

I have an model I reference in a DbContext class I'm using to generate my code-first DB. Originally the model was named FeedEventDomainModel and I changed the name to FeedEventCommand.I haven't generated the DB yet; however when I run the application to open Index.html under the areas folder, I receive the following error:
Code:
DbContext Class
using System.Data.Entity;
namespace OProj.DataContext
{
public class OProjDBContext : DbContext
{
public OProjDBContext() : base("name=OProjDB")
{
}
public DbSet<FeedEventCommand> FeedEvents { get; set; }
}
}
FeedEventCommand
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace OProj.DataContext
{
public class FeedEventCommand
{
[Key]
public int Id { get; set; }
public int AnimalId { get; set; }
public int FeederTypeId { get; set; }
public string FeederType { get; set; }
}
}
My question is since I changed the name of my model from FeedEventDomainModel to FeedEventCommand, is there a place in cache I need to clear so it doesn't keep referencing the old model name?
do a full clean.
close Visual Studio
delete the temp files in Windows/Microsoft.Net/Framework and Framework64/v4.0/Temporary ASP.NET Files
reopen the solution in VS, rebuild and it should work.
renaming things has that kind of effect so you have to delete the cached files

Updating Multiple Databases MVC 5

I have two contexts working with visual studio 2013. The one for the IdentityModel and another context I created for the main database. The problem I am having is whenever I run the update-database in the package manager console, it creates the ApplicationDBContext DB in both. The one for my main database never gets created because it seems it sees it as the ApplicationDBContext. I have tried Enable-Migrations -ContextTypeName DI_MVC.Models.DIDBContext and it does not create the main database tables for the DIDBContext class. I was able to do this in visual studio 2012 without an issue in creating the database. That was without the ApplicationDBContext though. Any help on what I am doing wrong would be greatly appreciated.
Below are my 2 code files. The normal IdentityModel and my DIDBContext class I created. Also I will display the web.config file as well with the database connections. There are 2 .mdf files that get created within the App_Data folder but both databases contain the membership tables.
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace DI_MVC.Models
{
public class DIDBContext : DbContext
{
public DIDBContext()
: base("DIDBContext")
{
}
public DbSet<DI_ConnectionStrings_CSI> CSIs { get; set; }
public DbSet<DI_DropDownValues_DDV> DDVs { get; set; }
public DbSet<DI_Types_DIT> DITs { get; set; }
public DbSet<DI_FORM_DIF> DIFs { get; set; }
public DbSet<DI_FormTabs_DFT> DFTs { get; set; }
public DbSet<DFI_FormSections_DFS> DFSs { get; set; }
public DbSet<DI_FormElements_DFE> DFEs { get; set; }
public DbSet<DI_DFE_DFS_DDD> DDDs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DI_DFE_DFS_DDD>().HasKey(k => new { k.DDD_DFS_ID, k.DDD_DFE_ID });
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace DI_MVC.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
}
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DI_MVC-meohmeohmy.mdf;Initial Catalog=aspnet-DI_MVC-meohmeohmy;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="DIDBContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DI_MVC-MainDB.mdf;Initial Catalog=aspnet-DI_MVC-MainDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You're not alone. It would make sense that if you enabled migrations for a single DbContext it would only update the DbContext that migrations are enabled for or at least let you specify which DbContext you wanted to update. However, that is not the case.
Read - this and this.
TLDR Enable-Migrations –EnableAutomaticMigrations

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.

EF Code First Not Generating Tables

I'm working on an EF Code first site, and I've written my classes and a context class, the source of which is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using MySite.SalesTool.Data.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MySite.SalesTool.Data
{
public class SalesToolEntities : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<JobAssigner> JobAssigners { get; set; }
public DbSet<JobFile> JobFiles { get; set; }
public DbSet<JobStatus> JobStatuses { get; set; }
public DbSet<AssignedUser> AssignedUsers { get; set; }
}
}
The project builds fine, but when I go to run the site, no tables are created in the database and I get an error stating that the database can't find whichever context object I try and access, presumably because the code first has not generated any of the necessary tables.
Any ideas why it wouldn't generate any of the tables at all, and not give me any kind of error information?
Do you have an initialization strategy?
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesToolEntities>());
From what you subscribe it sounds like you've created the database yourself. Then you need to specify an initialization
strategy otherwise no tables/data will be added to the database and querying the database will result in an exception: {"The specified table does not exist. [ sometable ]"}

Resources