Adding a new record by using EntityFramework - c#

I am creating a test project in order to learn using asp.net 5 and the mvc 6 framework.
I have decided to create a simple webpage that each menu item comes from the database. To do so I have created a model like such
namespace TestTemplate.Models
{
public class SideMenuItem
{
public int Id { get; set; }
public string Level { get; set; }
public string Label { get; set; }
public string Link { get; set; }
}
}
Inside my Models folder I also have a file named `TestContext.cs'
namespace TestTemplate.Models
{
public class TestContext : DbContext
{
public DbSet<SideMenuItem> SideMenuItems { get; set; }
}
}
That is my EntityFramework DbContext class.
When trying to create a new SideMenu item by using a simple view with a form to adding all the needed data, then using my angular factory that looks like this
return $resource('/api/sidemenu/:id');
I get the error:
An exception of type 'Microsoft.Data.Entity.DbUpdateException' occurred in EntityFramework.Core.dll but was not handled in user code
Additional information: An error occurred while updating the entries. See the inner exception for details.
-->System.Data.SqlClient.SqlException: Invalid object name 'SideMenuItem'.
This error occurs on SideMenuController.cs where I define my API at the part where I am trying to Post the new item:
[HttpPost]
public IActionResult Post([FromBody]SideMenuItem sideMenuItem)
{
if (sideMenuItem.Id == 0)
{
_dbContext.SideMenuItems.Add(sideMenuItem);
_dbContext.SaveChanges(); // ERROR HERE.
return new ObjectResult(sideMenuItem);
}
else
{
var original = _dbContext.SideMenuItems.FirstOrDefault(m => m.Id == sideMenuItem.Id);
original.Level = sideMenuItem.Level;
original.Label = sideMenuItem.Label;
original.Link = sideMenuItem.Link;
_dbContext.SaveChanges();
return new ObjectResult(original);
}
}
I also should mention that before running the app i used
>dnx ef migration add initial
>dnx ef database update
I believe it has to do with me not creating my database correctly. Since I am not seeing any folder on my project that had anything to do with databases or migrations.
Why is it complaining that SideMenuItem is invalid, and how can I fix the issue?

After trying to create my database again, I noticed that I had a typo on my migration command, hence the database was not created.
The command should have been dnx ef migrations ... with an s.
A good starting point with all the commands can be found here.

Related

Cannot add Scaffold > MVC Controller with views, using Entity Framework in Asp.NET Core

When I try to add Controller using build-in generator I get following error message:
Where "Brand" is a model class and "ApplicationDbContext" is my data context class.
I never encoutered error like this before. It does not occur all the time (2 success vs 30-40 attempts without changing single line of code). I was able to create Controller for same class minutes ago, but it's really annoying when you try to add something new and try more than 10 times with no results.
Of course, I could write my own controller and views, but I really like using included tools.
I have already repaired VS using "Modify" option in "Add or remove". I'm using latest Microsoft Visual Studio Community (MVSC2015 V14.0.25425.01 Update3).
EDIT:
Brand.cs:
namespace AppBrander.Models
{
public class Brand
{
public int ID { get; set; }
public string Email { get; set; }
public string BrandName { get; set; }
public string CompanyName { get; set; }
public string Description { get; set; }
}
}
Works in brand new project, fails in old - I guess it's just my VS installation being totally messed up. I should have been guessed, but I just did second repair...

C# WCF - ADO.NET Entity model - DbSet empty?

I created a new WCF project in visual studio based on a existing database.
I made two operations. One operation writes a record (createProfile) to the database and one retrieve data (GetProfiles). My project exists of 3 files: web.config, a edmx file and my svc class.
CreateProfile works fine, I checked in SQL and the record is created.
GetProfiles never gives a response. When I debug the context.UserProfileSet always counts 0 values.
Any suggestions on what is going wrong?
[DataContract]
public partial class UserProfile
{
public int Id { get; set; }
[DataMember]
public string UserName { get; set; }
}
public class MusicOwnerService : IMusicOwnerService
{
IEnumerable<UserProfile> GetProfiles()
{
using (MusicOwnerDatabaseEntities context = new MusicOwnerDatabaseEntities())
{
return context.UserProfileSet.AsEnumerable();
}
}
public void CreateProfile()
{
using (MusicOwnerDatabaseEntities context = new MusicOwnerDatabaseEntities())
{
context.UserProfileSet.Add(new UserProfile { UserName = "John" });
context.SaveChanges();
}
}
}
As far as I know, you cant pass an IEnumerable object over the wire with WCF (unless youve a duplex binding of some sort??).. so you would be best to convert to a list and return that list like below:
List<UserProfile> GetProfiles()
{
using (MusicOwnerDatabaseEntities context = new MusicOwnerDatabaseEntities())
{
return context.UserProfileSet.ToList();
}
}

Error creating MVC 4 controller

I'm getting an error "Unable to retrieve Metadata for "TeamAssignment.Models.Test. Unable to cast object of type "System.Data.Entity.Core.Objects.ObjectContext" to type "System.Data.Objects.ObjectContext."
This is happening whenever I try to create a controller with action/views with the code first entity framework. I'm trying it with a simple test class that's not related to my project and even that is not getting through.
namespace TeamAssignment.Models
{
public class Test
{
[Key]
public int id { get; set; }
public string test { get; set; }
}
public class testDBContext : DbContext
{
public DbSet<Test> testing { get; set; }
}
}
Am I being retarded here or is something wrong with my overall program? I was having some issues with TFS earlier and I'm trying to determine if its related to that.
Sounds like you recently upgraded to EF6.
Unfortunately the MVC 4 scaffolding tools are not compatible with EF6 and there's nothing you can do except upgrade to MVC5 (if possible).

MVC 4.0 Controller cannot find seeded data

I am attempting to seed data for an MVC 4 project using SQL server 4.0 as the database engine, using the Microsoft MVC music store tutorial as an example. I have set up a seed and DB context models, but the controller is not able to find the data. I have verified that the the database file is created in App_Data and verified that SetIntitializer is correctly set up in Application_Start. Here is what I have for code:
Seed data:
namespace RationalMethodApp.Models
{
public class StartData : CreateDatabaseIfNotExists<RationalMethodEntities>
{
protected override void Seed(RationalMethodEntities context)
{
new List<Basin>
{
new Basin {
basinId = 1, // attempting to force a key value, will remove
Name = "Replace me with a real basin",
Location = "In a real location",
drainageArea = 0.0M
}
}.ForEach(b => context.Basins.Add(b));
Controller:
public ActionResult Index(int? bsnId)
{
if (bsnId == null) // here to force a key value, will change
bsnId = 1;
var basin = rmDb.Basins.Find(bsnId);
return View(basin);
}
The context class is:
namespace RationalMethodApp.Models
{
public class RationalMethodEntities : DbContext
{
public DbSet<Basin> Basins { get; set; }
public DbSet<SubArea> SubAreas { get; set; }
public DbSet<IdfCurve> IdfCurves { get; set; }
public DbSet<Analysis> Analyses { get; set; }
public DbSet<FlowSegment> FlowSegments { get; set; }
public DbSet<SheetFlowN> SheetFlowNs { get; set; }
public DbSet<RunoffCoefficient> RunoffCoefficients { get; set; }
public DbSet<StormFrequency> stormFrequencies { get; set; }
}
}
The debugger tells me that the "basin" object is still null in the controller after the .Find. This must be a simple, basic thing that I have overlooked, but all of the help I can find on-line assumes that the askers know what they are doing - not true in my case! I have also checked the discussion at Entity Framework database seed doesn't seed
but this does not seem to be the answer. Please bear with a total noob question.
You don't show the full code of you seed, so i can't really be sure, but you might be missing the Context.Changes().
As well you wrote
public class StartData : CreateDatabaseIfNotExists<RationalMethodEntities>
If you don't delete your database before the application start, it won't do anything as the db already exists.
You could use :
public class StartData : DropCreateDatabaseAlways <RationalMethodEntities>
to drop it every time you start or
public class StartData : DropCreateDatabaseAlways <DropCreateDatabaseIfModelChanges >
to drop db when Model changes (which is great for start of dev)
To debug: Drop your database, kill your application server (so it goes back to application start), breakpoint in your seed. Start Debug, if it goes in seed, check that data is in it after SaveChange().

Listing table results in "CREATE TABLE permission denied in database" ASP.NET - MVC4

I'm using ASP.NET MVC 4 - c# to connect to a live database, and list the results, however when I go to view the page it returns the following error:
CREATE TABLE permission denied in database 'DatabaseName'.
Description: An unhandled exception occurred during the execution
of the current web request. Please review the stack trace for more
information about the error and where it
originated in the code.
Exception Details: System.Data.SqlClient.SqlException: CREATE TABLE
permission denied in database 'DatabaseName'.
Source Error:
Line 16: public ActionResult Index()
Line 17: {
Line 18: return View(db.AccControls.ToList());
Line 19: }
Line 20
Controller:
namespace TestDBCon.Controllers
{
public class HomeController : Controller
{
private DataDbContext db = new DataDbContext();
public ActionResult Index()
{
return View(db.AccControls.ToList());
}
}
}
AccControl.cs (model)
namespace TestDBCon.Models
{
public class AccControl
{
public int ID { get; set; }
public int ControlCode { get; set; }
public string Nominal { get; set; }
public string CostCentre { get; set; }
public string Department { get; set; }
}
public class DataDbContext : DbContext
{
public DbSet<AccControl> AccControls { get; set; }
}
}
Web.Config:
<add name="DataDbContext" connectionString="Data Source=***;initial catalog=***;integrated security=True;" providerName="System.Data.SqlClient" />
I'm not trying to create a table? I'm just trying to list results so I'm extremely confused. It must be something to do with the MVC?
Any help would be greatly appreciated!
Thanks
I know it's old but since I had the same problems and it took me a while to find the solution... I decided to share the info. So I had to do 2 things to get rid of this problem, 1st was disabling the migrations:
# Migrations/Configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<IntranetApplication.Models.MyDb1>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
however that wasn't enough, I also had to make sure the Seeder doesn't run. You can cancel it with this extra piece of code:
#Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
Database.SetInitializer<Models.MyDb1>(null);
Database.SetInitializer<Models.MyDb2>(null);
...
}
Then finally I can now do a SELECT with LINQ and only have READ access
EDIT
As per Lawrence's suggestion, it's most probably better having it directly inside DB Context Constructor. Thanks for the tip, I updated my code and it now looks like this:
public partial class MyDb1 : DbContext
{
public MyDb1()
: base("name=MyDb1Connection")
{
Database.SetInitializer<Models.MyDb1>(null);
}
...
}
Is your web config pointing to the correct database?
Are the credentials correct?
Entity Framework will create tables in the database if you are going to use the MVC4 WebSecutiy() to handle the Authentication and Authorisation of users. This could be throwing the exception.
In this case where you cannot create the tables needed for the membership provider, you will need to exclude this from the system. See this here. Alternatively create a new MVC4 project and select empty template and just put in the bits you need.
I encountered a similar error after refactoring and renaming some code. The issue was that my C# code didn't match table name in the Database.
My code in c#:
public virtual DbSet<MyTableName>
And the table name in SQL Server:
MyActualTableName
Since the table names didn't match (MyTableName != MyActualTableName), I got this (misleading) error:
Create TABLE permission denied in database MyDatabase
Took me awhile to see what I'd messed up, but matching the table names resolved the error.

Categories