简体   繁体   中英

code first Entity Framework not saving to database

Ok, I am doing a project with entity framework 6. I have my class laid out. When I try to add the information to the database; it gives me following errors:

The best overloaded method match for 'System.Data.Entity.DbSet<img_site_codefi.DAL.DefaultConnection>.Add(img_site_codefi.DAL.DefaultConnection)' has some invalid arguments

Argument 1: cannot convert from 'AnonymousType#1' to 'img_site_codefi.DAL.DefaultConnection'

Here is my controller:

public ActionResult Contact(customer cust)
{
    try
    {
        if (ModelState.IsValid)
        {
            cust.Tele_comp();
            saveIntoDb(cust); // database
            SendMail(cust); // mail sender
            return RedirectToAction("Submited", "Home");
        }
        return null;
    }
    catch (DataException)
    {
        return View(cust);
    }
}

private void saveIntoDb(customer cust)
{
    using (var cust_In = new DefaultConnection())
    { 
        var customer = new {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };
        //cust_In.customers.Add(customer); //HERE IS THE ERROR!!!
        cust_In.SaveChanges();
    }    
}

and here is the model:

    [Key]
    [] // how to assign a number automatically 
    public int Cust_Id { get; set; } 
    [Required(ErrorMessage = "first name is required!")]
    [Display(Name = "First name")]
    public string fname { get; set; }
    [Display(Name = "Last name")]
    public string lname { get; set; }

    [Required(ErrorMessage = "area code is required!")]
    [StringLength(3)]
    [RegularExpression(@"^[0-9]{3,}$", ErrorMessage = "Minimum 3 numbers required & contain only numbers")]
    [Display(Name = "Telephone")]
    public string tel_area { get; set; }

    [Required(ErrorMessage = "first three numbers are required!")]
    [StringLength(3)]
    [RegularExpression(@"^[0-9]{3,}$", ErrorMessage = "Minimum 3 numbers required & contain only numbers")]
    public string fir_thr_tel { get; set; }

    [Required(ErrorMessage = "last four numbers are required!")]
    [StringLength(4)]
    [RegularExpression(@"^[0-9]{4,}$", ErrorMessage = "Minimum 4 numbers required & contain only numbers")]
    public string lst_fur_tel { get; set; }

    [Required(ErrorMessage = "E-mail is required!")]
    [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
    [Display(Name = "Email")]
    public string email { get; set; }
    [Required(ErrorMessage = "A reason is required!")]
    [Display(Name = "Reason")]
    public string reasn { get; set; }

    public string tele { get; set; }

Also, how do I generate a number automatically for the "Cust_Id" like a database do with the sql code IDENTITY or computed.

You have 2 problems. First, this line is wrong:

var customer = new {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };

You are creating an anonymous type instead of a customer object. Try this instead:

var customer = new customer 
{
    fname = cust.fname,
    lname = cust.lname, 
    tele = cust.tele, 
    email = cust.email, 
    reasn = cust.reasn 
};

Secondly your context DefaultConnection is wrong and contains this:

public DbSet<DefaultConnection> customers { get; set; }

You are creating a DbSet of your context class instead of customer s. This should be:

public DbSet<customer> customers { get; set; }

You cannot add Anonymous typed class or Dynamic to a DbSet so you need to create an instance class of customer in order to be added to your DbSet.

public ActionResult Contact(Customer cust)
{
    try
    {
        if (ModelState.IsValid)
        {
            cust.Tele_comp();
            saveIntoDb(cust); // database
            SendMail(cust); // mail sender
            return RedirectToAction("Submited", "Home");
        }
        return null;
    }
    catch (DataException)
    {
        return View(cust);
    }
}

private void saveIntoDb(Customer cust)
{
    using (var cust_In = new DbContext())
    { 
        var customer = new Customer {fname = cust.fname,lname = cust.lname, tele = cust.tele, email = cust.email, reasn = cust.reasn };
        cust_In.Customers.Add(customer); //HERE IS THE ERROR!!!
        cust_In.SaveChanges();
    }    
}

Also your DbContext.cs class should have this instead of your code:

public DbSet<Customer> Customers { get; set; }

For the generation of primary key you should use this:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Make sure you try this tutorial first: http://msdn.microsoft.com/en-us/data/jj572366.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM