Error of Database.Table Objet is invalid - c#

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I've created 2 models (User & Poste) with their controllers (UserController & PosteController) thanks to the method of creation with 'Read/Write actions and views, using Entity Framework'.
When i would like to access to the view of User or Poste, that's mean when I put /Poste (or /User) in my URL to access to the index, this error appears to me :
Object Name 'dbo.Poste' invalid. or Object Name 'dbo.User' invalid.
This is the model of User :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data.Entity;
namespace MvcApplication2.Models
{
public class User
{
[Required]
[Key]
[Display(Name = "Matricule :")]
public string Matricule { get; set; }
[Required]
[Display(Name = "Nom :")]
public string Nom_User { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Le {0} doit avoir au minimum {2} caractères.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Mot de passe :")]
public string passWord { get; set; }
[Required]
[Display(Name = "Type :")]
public string Type_User { get; set; }
[Required]
[Display(Name = "ID_UF :")]
public string ID_UF { get; set; }
}
}
this is the Controller of User :
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class UserController : Controller
{
private GammeContext db = new GammeContext();
//
// GET: /User/
public ViewResult Index()
{
return View(db.Users.ToList());
}
//
// GET: /User/Details/5
public ViewResult Details(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// GET: /User/Create
public ActionResult Create()
{
return View();
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
//
// GET: /User/Edit/5
public ActionResult Edit(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
//
// GET: /User/Delete/5
public ActionResult Delete(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// POST: /User/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(string id)
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
and this the context Class (GammeContext) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication2.Models
{
public class GammeContext:DbContext
{
public DbSet<Poste> Postes { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
}
and this is what I added in my web.config file :
<add name="GammeContext" connectionString="Data Source=SWEET-DE396641E\SQLEXPRESS;database=Flux; Integrated Security=true" providerName="System.Data.SqlClient" />

check database whether User table exist or not by writing this query in new query editor window:
select * from dbo.User
may be you are able to run this:
select * from User
it is because this table schema is attached with your default user rather than 'dbo' object.
To fixed this you need to copy User to dbo.User by running following query:
select * into dbo.User from User

Related

Mvc creating route attribute

I want to create a route attribute in the Porosi controller, in the detaje method that takes as a DatePorosie (DatePorosie is the date) on parameter. The method must display from Porosi.cs class EmriPorosise, DatePorosie, TotaliPorosise according to the date that comes as a parameter in url. (sending date value either by form or by link). I hope I explained it well. Can you help me please???
This is Porosi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcProjektDb.Models
{
public class Porosi
{
public int PorosiId { get; set; }
public string EmriPorosise { get; set; }
public DateTime DatePorosie { get; set; }
public int TotaliPorosise { get; set; }
public int? KlienteId { get; set; }
public virtual Kliente Kliente { get; set; }
}
}
This is PorosiController.cs but I don't know what to do here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcProjektDb.Migrations;
using MvcProjektDb.Models;
namespace MvcProjektDb.Controllers
{
public class PorosiController : Controller
{
private ApplicationDbContext _db;
public PorosiController()
{
_db = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
}
// GET: Porosi
public ActionResult Index()
{
return View();
}
[Route("Porosi/detaje/{dateporosie?}")]
public ActionResult detaje(DateTime? dateporosie)
{
var x = _db.porosi.Where(p => p.DatePorosie == dateporosie).ToList();
return View(x);
}
}
}

CS0118 error in controller from model in asp.net [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm creating a database with the entity framework, I created the first entity as a carlot and the second car which will list the cars in the respective lots. I keep thinking something is wrong with my model ... here is following model
namespace CarLot.Models
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
public class CarModel : DbContext
{
public CarModel()
: base("name=CarModel")
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
public DbSet<CarLot> CarLots { get; set; }
public DbSet<Car> Cars { get; set; }
}
public class CarLot
{
//Primary Key
public int CarLotID { get; set; }
public string Name { get; set; }
public string Section { get; set; }
public virtual ICollection<Car> Cars { get; set; }
}
public class Car
{
public int CarId { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public int Price { get; set; }
public bool isNew { get; set; }
//foreign key
public int CarLotID { get; set; }
public virtual CarLot Carlot { get; set; }
}
}
I proceeded to scaffold the controller for Cars, that does not show any errors.
but not my carlot, this is the following CarLot file... its giving me the CS0118 error with CarLot as commented below, 6 following CarLot giving me the CS0118 which states "CarLot is a namespace but is used as a type"
sing System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CarLot.Models;
namespace CarLot.Controllers
{
public class CarLotsController : Controller
{
private CarModel db = new CarModel();
// GET: CarLots
public ActionResult Index()
{
return View(db.CarLots.ToList());
}
// GET: CarLots/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// It is giving me the CS0118 error with the following CarLot
CarLot carLot = db.CarLots.Find(id);
if (carLot == null)
{
return HttpNotFound();
}
return View(carLot);
}
// GET: CarLots/Create
public ActionResult Create()
{
return View();
}
// POST: CarLots/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarLotID,Name,Section")] CarLot carLot)
{
if (ModelState.IsValid)
{
db.CarLots.Add(carLot);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(carLot);
}
// GET: CarLots/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CarLot carLot = db.CarLots.Find(id);
if (carLot == null)
{
return HttpNotFound();
}
return View(carLot);
}
// POST: CarLots/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarLotID,Name,Section")] CarLot carLot)
{
if (ModelState.IsValid)
{
db.Entry(carLot).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(carLot);
}
// GET: CarLots/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CarLot carLot = db.CarLots.Find(id);
if (carLot == null)
{
return HttpNotFound();
}
return View(carLot);
}
// POST: CarLots/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
CarLot carLot = db.CarLots.Find(id);
db.CarLots.Remove(carLot);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
namespace CarLot.Models
{
public class CarLot
{
The problem relates this code both namespace and class name is CarLot
Try changing one of them

Null entry for parameter Id/Can't add data from other model into view

I'm new to learning asp.net and I'm trying to output table data from two different tables in one view. I'm getting the following error
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'Vidly12.Controllers.CustomerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This line of code is triggering the error
#Model.MembershipType.MembershipName
in the Details.cshtml
I can't figure out how integrate this table and its data into table. The MembershipName outputs correctly in the CustomerView.chtml so it's associating the customer to the membership name correctly for that view, but not in the Details.cshtml view. Any help is appreciated. Let me know if any additional information is needed
Details.cshtml
#model Vidly12.Models.Customer
#using Vidly12.Models
#{
ViewBag.Title = "Details";
}
<h2>#Model.Name</h2>
<ul>
<li>#Model.MembershipType.MembershipName</li>
<li>#Model.BirthDate</li>
</ul>
CustomerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly12.Models;
using System.Data.Entity;
using Vidly12.ViewModel;
namespace Vidly12.Controllers
{
public class CustomerController : Controller
{
private ApplicationDbContext _context;
public CustomerController()
{
_context = new ApplicationDbContext();
}
public ActionResult CustomerView()
// GET: Customeriew(int id)
{
var customer = _context.Customer.Include(c => c.MembershipType).ToList();
return View(customer);
}
public ActionResult Details(int id)
{
var customer = _context.Customer.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
}
}
Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vidly12.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public MembershipType MembershipType { get; set; }
}
}
MembershipType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vidly12.Models
{
public class MembershipType
{
public byte Id { get; set; }
public string MembershipName { get; set; }
public byte Duration { get; set; }
public byte DiscountRate { get; set; }
}
}
CustomerView.cshtml
In your Details.cshtml view, you have this line of code:
#Model.MembershipType.MembershipName
But you are passing this as the model to the above view:
var customer = _context.Customer.SingleOrDefault(c => c.Id == id);
The MembershipType property is null so you are getting the error. You need to do this to eagerly load the MembershipType property:
var customer = _context.Customer.Include(
c => c.MembershipType).SingleOrDefault(c => c.Id == id);

While checking whether the user exists in the database "The entity type User is not part of the model for the current context"

While checking whether the user exists in the database, this happens "The entity type User is not part of the model for the current context".
"Sorry for my bad english"
This my Context:
public class UserContext : DbContext
{
public UserContext() :
base("PracticeDB")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PracticeDB>().ToTable("Users");
}
public DbSet<User> Users { get; set; }
}
View model:
namespace Models.Models
{
public class LoginModel
{
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
Controller:
namespace Models.Controllers
{
public class AccountController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
User user = null;
using (UserContext db = new UserContext())
{
user = db.Users.FirstOrDefault(u => u.Name == model.Name && u.Password == model.Password);
}
if (user != null)
{
FormsAuthentication.SetAuthCookie(model.Name, true);
return RedirectToAction("Users");
}
else
{
ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
}
}
return View(model);
}
}
}
enter image description here
I think this line in your UserContext:
modelBuilder.Entity<PracticeDB>().ToTable("Users");
Needs to change to:
modelBuilder.Entity<User>().ToTable("Users");
You need to tell the DbContext about the User model in OnModelCreating. Try changing the PracticeDB model to User in modelBuilder.Entity<PracticeDB>().ToTable("Users");.

Access not possible for my index

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I've created 2 models (User & Poste) with their controllers (UserController & PosteController) thanks to the method of creation with 'Read/Write actions and views, using Entity Framework'.
Everything goes well for the Poste, I can create, edit, delete...
The problem is related to the User. In fact, when I put /User in my URL to access to the index, this error appears to me :
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: Nom d'objet
'dbo.Users' non valide.
This is User model code :
public class User
{
[Required]
[Key]
[Display(Name = "Matricule :")]
public string Matricule { get; set; }
[Required]
[Display(Name = "Nom :")]
public string Nom_User { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Le {0} doit avoir au minimum {2} caractères.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Mot de passe :")]
public string passWord { get; set; }
[Required]
[Display(Name = "Type :")]
public string Type_User { get; set; }
[Required]
[Display(Name = "ID_UF :")]
public string ID_UF { get; set; }
}
public class GammeDBContext : DbContext
{
public DbSet<User> Users { get; set; }
}
and this is the UserController code :
public class UserController : Controller
{
private GammeDBContext db = new GammeDBContext();
//
// GET: /User/
public ViewResult Index()
{
return View(db.Users.ToList());
}
//
// GET: /User/Details/5
public ViewResult Details(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// GET: /User/Create
public ActionResult Create()
{
return View();
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
//
// GET: /User/Edit/5
public ActionResult Edit(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
//
// GET: /User/Delete/5
public ActionResult Delete(string id)
{
User user = db.Users.Find(id);
return View(user);
}
//
// POST: /User/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(string id)
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
and this is what I added in my web.config file :
<add name="GammeDBContext"
connectionString="Data Source=SWEET-DE396641E\SQLEXPRESS;database=Flux; Integrated Security=true"
providerName="System.Data.SqlClient" />
<add name="GammeDBContextP"
connectionString="Data Source=SWEET-DE396641E\SQLEXPRESS;database=Flux; Integrated Security=true"
providerName="System.Data.SqlClient" />
PS :
GammeDBContext is for the 'User'
GammeDBContextP is for the 'Poste'
So is there any solution ?
is your database table called 'User'? If it is, try throwing this code in with your context class.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
This bugged the bajeezus out of me one time.
Also why do you have 2 identical connection strings?

Categories

Resources