Access not possible for my index - 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'.
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?

Related

ModelState.IsValid returns False even if the required property is valid

ModelState.IsValid returns false even if the properties with Required annotation have valid values. I logged the string representation of the object and it shows that the Username and Password is not empty.
User Model
public class User
{
public int Id { get; set; }
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public override string ToString()
{
return $"Username: {Username}, Password: {Password}";
}
}
Controller
public class AuthController : Controller
{
private readonly UserContext _context;
private readonly ILogger<User> _logger;
[BindProperty]
public User AuthUser { get; set; }
public AuthController(ILogger<User> logger, UserContext context)
{
_logger = logger;
_context = context;
}
public IActionResult Login()
{
return View(new User());
}
[HttpPost]
public async Task<IActionResult> Login(string returnURL = null)
{
if (!ModelState.IsValid)
{
_logger.LogInformation(AuthUser.ToString());
//Executes this block even if Username and Password has data
}
}
public IActionResult Login()
{
return View(new User());
}
[HttpPost]
public async Task<IActionResult> Login(User model,string returnURL = null)
{
if (ModelState.IsValid)
{
_logger.LogInformation(model.ToString());
}
return View(model);
}
I had the same problem for a long time and finally I found it. In my case, it was the Id field :)
Just place a breakpoint and check your ModelState in runtime and go to this section :
ModelState -> Root -> Children
and you will see all valid and invalid Keys
There may be issues with int fields.
In your case, that could be the Id field.
As we know, integer can not be null and if in view page we have set its value to empty, it will be marked as invalid in the ModelState in the post method. Because, int can not be null/empty.

send JSON Object in ASP .NET

i am trying te sent an object in JSON format but the method always get a null object
here is the ERROR :
Server Error in '/' Application.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
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.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source Error:
Line 15: context = ApplicationDbContext.Create();
Line 16: context.Users.Add(user);
Line 17: if (context.SaveChanges() == 0)
Line 18: {
Line 19: context.Dispose();
Source File: D:\Education\Git\Online-Store-Platform-API\OnlineStorePlatform\OnlineStorePlatform\DBContext\UserContext.cs Line: 17
and that is my code :
public class AccountController : Controller
{
//public UserDTO user;
public UserContext myContext;
// GET: Account
public ActionResult Index()
{
return View();
}
//[HttpPost]
public ActionResult Register([FromBody]UserDTO user)
{
//user = new UserDTO(email, password, userName);
myContext = new UserContext();
if (myContext.addUser(new User(user)) == null) return Content("ERROR");
return Content("Created Successfully");
}
}
when ever i sent an UserDTO object always get null
my request :
UseDTO class:
public class UserDTO
{
public String email, userName, password;
public UserDTO(String email, String password, String userName)
{
this.email = email;
this.password = password;
this.userName = userName;
}
public UserDTO() { }
}
when i try debugging i got a null object
Convert email, username and password to property.
public string Email { get; set;}
public class AccountController : Controller
{
public UserContext myContext;
public AccountController () : this(new UserContext()) {}
public AccountController (UserContext _myContext)
{
myContext = _myContext;
}
// GET: Account
public ActionResult Index()
{
return View();
}
public ActionResult Register(UserDTO user)
{
if (ModelState.IsValid) {
myContext.Add(User);
//ToDo: Redirect or many options
}
return View(user);
}
}
Edit:
This is important
public class UserDTO
{
public String email { get; set; }
public String userName { get; set; }
public String password { get; set; }
}
Ok i found the solution to my problem..
the problem is that i am inherting from class Controller but i should inhert from ApiController .
public class AccountController : Controller
{
........
}
it worked after that.. thank you all

EntityType no keys defined

I'm creating an app where users log in via Facebook oAuth and then set up a list of songs. I am getting the following error message:
BandFinderCsharp.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
BandFinderCsharp.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
The error message is occurring within my SongsController:
`namespace BandFinder.Controllers.Bread
{
public class SongsController : Controller
{
private SongDBContext db = new SongDBContext();
// GET: Songs
public ActionResult Index()
{
return View(db.Songs.ToList()); <--- This is where the error occurs
}
// GET: Songs/Details/5
public ActionResult Details(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Song song = db.Songs.Find(id);
if (song == null)
{
return HttpNotFound();
}
return View(song);
}
// GET: Songs/Create
public ActionResult Create()
{
return View();
}
// POST: Songs/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,UserId,BandId,Title,Artist,Genre,ListId,CreatedOn")] Song song)
{
if (ModelState.IsValid)
{
song.CreatedOn = DateTime.Now;
db.Songs.Add(song);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(song);
}
// GET: Songs/Edit/5
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Song song = db.Songs.Find(id);
if (song == null)
{
return HttpNotFound();
}
return View(song);
}
// POST: Songs/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 = "Id,UserId,BandId,Title,Artist,Genre,ListId,CreatedOn")] Song song)
{
if (ModelState.IsValid)
{
db.Entry(song).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(song);
}
// GET: Songs/Delete/5
public ActionResult Delete(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Song song = db.Songs.Find(id);
if (song == null)
{
return HttpNotFound();
}
return View(song);
}
// POST: Songs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
Song song = db.Songs.Find(id);
db.Songs.Remove(song);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}`
The thing I don't understand is, this controller has nothing to do with the IdentityUser code..
This is my ApplicationUser Model:
namespace BandFinderCsharp.Models
{
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreatedOn = DateTime.Now;
this.ProfileImage = new byte[0];
this.facebookImage = new byte[0];
}
public byte[] facebookImage { get; set; }
[MaxLength(32)]
public string FirstName { get; set; }
[MaxLength(32)]
public string LastName { get; set; }
public byte[] ProfileImage { get; set; }
//public virtual ICollection<Instrument> Instruments { get; set; }
//public virtual ICollection<Song> Songs { get; set; }
//public virtual ICollection<Band> Bands { get; set; }
public string Zipcode { get; set; }
[Index]
public float Longitude { get; set; }
[Index]
public float Latitude { get; set; }
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime CreatedOn { get; set; }
//////////////
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
base.OnModelCreating(modelBuilder);
}
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Why am I getting an error referring to Identity models from the songs controller? There should be no correlation between the two at this point.
The IdentityUser class is a built in .NET class which I don't believe I'm able to edit:
namespace Microsoft.AspNet.Identity.EntityFramework
{
//
// Summary:
// Default EntityFramework IUser implementation
public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
{
//
// Summary:
// Constructor which creates a new Guid for the Id
public IdentityUser();
//
// Summary:
// Constructor that takes a userName
//
// Parameters:
// userName:
public IdentityUser(string userName);
}
}
IdentityUserLogin
namespace Microsoft.AspNet.Identity.EntityFramework
{
//
// Summary:
// Entity type for a user's login (i.e. facebook, google)
public class IdentityUserLogin : IdentityUserLogin<string>
{
public IdentityUserLogin();
}
}
If the ApplicationUser class is the object you're looking to save in the Data Base, then it must contain a field named Id which is by default the primary key of the object to which Entity Framework is linking to.
Your Object should look like:
public class ApplicationUser
{
public int Id { get; set; }
public string Name { get; set; }
}
Or if you want to set a different property as the primary key for the object, you should add the [Key] attribute above that field - and you'll also need to add the System.ComponentModel.DataAnnotations namespace:
public class ApplicationUser
{
public int Id { get; set; }
[Key]
public string Name { get; set; }
}
Looking at your entities, I am missing the [Key] attribute that defines the fields for the primary key.
Look at this question, first answer:
EntityType 'Category' has no key defined. Define the key for this EntityType

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");.

Error of Database.Table Objet is invalid

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

Categories

Resources