Reputation: 23
I'm working on ASP.NET MVC 4, and when I try to insert data into user table an error occurs:
The best overloaded method match for 'System.Data.Entity.DbSet.Add(PHARMACY.Models.User)' has some invalid arguments E:\Testing\PHARMACY\PHARMACY\Controllers\AdminController.cs 56 21 PHARMACY
This is my controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult CreateUser(Createuser cu)
{
if (ModelState.IsValid)
{
using (UserDB db = new UserDB())
{
db.users.Add(cu);
db.SaveChanges();
ModelState.Clear();
cu = null;
ViewBag.Message = "User Added Sucessfully";
return View();
}
}
else
{
}
}
This is my model
[Table("User")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Full_Name { get; set; }
[Required(ErrorMessage = "Please Provide Username", AllowEmptyStrings = false)]
public string Username { get; set; }
[Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
public string User_Type { get; set; }
public string Login_Status { get; set; }
}
public class Createuser
{
[Required(ErrorMessage = "Please Provide Fullname", AllowEmptyStrings = false)]
[Display(Name = "Full Name")]
public string Full_Name { get; set; }
[Required(ErrorMessage = "Please Provide Username", AllowEmptyStrings = false)]
public string Username { get; set; }
[Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please Select User type", AllowEmptyStrings = false)]
[Display(Name = "User Type")]
public string User_Type { get; set; }
[Required(ErrorMessage = "Please Select Login Status", AllowEmptyStrings = false)]
[Display(Name = "Login Status")]
public string Login_Status { get; set; }
}
public class UserDB : DbContext
{
public DbSet<User> users { get; set; }
}
Upvotes: 0
Views: 68
Reputation: 151586
Your db.users.Add()
method accepts a User
, yet you pass it a CreateUser
. That won't work.
You need to map the CreateUser
to a User
:
var user = new User
{
Full_Name = cu.Full_Name,
...
}
db.users.Add(user);
Upvotes: 1
Reputation: 17064
You are trying to add a Createuser
type to a User
type.
You are doing db.users.Add(cu);
when cu
is of type Createuser
. You'll need to do a transformation from Createuser
to User
first.
Upvotes: 0
Reputation: 3835
You can not put a CreateUser into a table that expects a User. They might have the same properties etc. put they are not the same type, so no dice.
No need to "convert" your CreateUser into a User object, and store that.
Upvotes: 0