我正在研究MVC 4,当我尝试将数据插入用户表时发生错误

时间:2015-01-05 12:55:21

标签: asp.net-mvc

我正在使用ASP.NET MVC 4,当我尝试将数据插入用户表时发生错误:

  

最佳重载方法匹配' System.Data.Entity.DbSet.Add(PHARMACY.Models.User)'有一些无效的参数E:\ Testing \ PHARMACY \ PHARMACY \ Controllers \ AdminController.cs 56 21 PHARMACY

这是我的控制者:

[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
        { 
        }
}

这是我的模特

[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; }
}

3 个答案:

答案 0 :(得分:1)

您的db.users.Add()方法接受User,但您将其传递给CreateUser。那不会起作用。

您需要将CreateUser映射到User

var user = new User
{
    Full_Name = cu.Full_Name,
    ...
}

db.users.Add(user);

答案 1 :(得分:0)

您不能将CreateUser放入需要用户的表中。它们可能具有相同的属性等等,因为它们不是同一类型,所以没有骰子。

无需将您的CreateUser“转换”为User对象,并将其存储。

答案 2 :(得分:0)

您正尝试将Createuser类型添加到User类型。

db.users.Add(cu);类型为cu时,您正在Createuser。您需要先从Createuser转换为User