HarshSharma
HarshSharma

Reputation: 660

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.

Upvotes: 1

Views: 1034

Answers (1)

StepUp
StepUp

Reputation: 38124

It looks like your model class is StudentRecordManagement.Models.StudentDetail, however you are inserting StudentRecordManagement.Models.StudentDetails. 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);  //
}

Upvotes: 3

Related Questions