简体   繁体   中英

Cannot convert from Models.Class to DbContext.Class using Entity Framework and ASP.NET MVC

I'm using a database first approach and I want to insert some data into the database. I am using this code:

public ActionResult Create(StudentDetails studentDetails)
{
    using (StudentRecordManagementEntities1 obj = new StudentRecordManagementEntities1())
    {
         obj.StudentDetails.Add(studentDetails);  //throws error
    }
}

Model class:

public class StudentDetails
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public Nullable<long> ContactNumber { get; set; }
    public string Address { get; set; }
    public decimal Fees { get; set; }
    public bool isPaid { get; set; }
}

Error details:

Error CS1503 Argument 1: cannot convert from 'StudentRecordManagement.Models.StudentDetails' to 'StudentRecordManagement.Models.StudentDetail' StudentRecordManagement*

If you need more details, kindly let me know.

It looks like your model class is StudentRecordManagement.Models.StudentDetail , however you are inserting StudentRecordManagement.Models.StudentDetail s . So what you can do is to give necessary type to your Database model:

public ActionResult Create(StudentDetails studentDetails)
{
    using (StudentRecordManagementEntities1 obj = new StudentRecordManagementEntities1())
    {
        var studentDetail = new StudentRecordManagement.Models.StudentDetail {
         Name = studentDetails.Name,
         // the other code is omitted for the brevity
     };
     obj.StudentDetails.Add(studentDetail);  //
}

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