Mark Tabor

Mark Tabor

  • 589
  • 2k
  • 460.1k

Model are not binging in getting record from db entity framework

Aug 6 2024 5:00 PM

I met with a small issue in my asp.net core mvc application I define viewmodel in my web project and I have separate dataaccesslayer where I have my models

My one class which is present in dataaccess with name Property having the following properties

public partial class Property
{
    public string PropertyId { get; set; } = null!;
    public string? Description { get; set; }
    public decimal? TypeId { get; set; }
    public decimal? Worth { get; set; }
    public decimal CountryId { get; set; }
    public virtual Category? Asset { get; set; }
    public virtual  Users? User { get; set; }
}

I have one viewmodel In which I have define few more entities with this entity as well because I have to show data from multiple table so I am using viewmodel

My View model code is below

using NuGet.ContentModel;
using Project_DATA_ACCESS.Models;
namespace Project_WEB.ViewModels
{
    public class Property
    {
        public string PropertyId { get; set; } = null!;
        public string? Description { get; set; }
        public decimal? TypeId { get; set; }
        public decimal? Worth { get; set; }
        public decimal CountryId { get; set; }
        public virtual Category? Asset { get; set; }
        public virtual  Users? User { get; set; }
    }
    Public class student
    {
        Public int studentID{get;set;}
        Public string studentName{get;set;}
    }
    public class MyWM
    {
        public string? name { get; set; }
        public string? familyname { get; set; }
        public decimal? productcode { get; set; }
        public Assets AssestD { get; set; }
        public MYWM()
        {
            Property = new Property ();
            Student=new Student();
        }
    }
}

You can see my Property class which is generated by entity framework in my model folder of data access layer and the property class which I have in viewmodel both having the same strucuture same number of columns with data type as well but in my controller index action method when I want to give the property the values from db it gives an error

MYWM model = new MYWM ();
MYWM.Property = DbContext.Property.ToList();

My Table is having name Property on this line I am getting this error

DbContext is not null here I am sure I am initializing the db context the error is basically below one

cannot implicitly convert type "System.Collection.Generic.List<Project.Data_Access.Model.Property"> to "Project_web.ViewModels.Property"

Why it is complaining they are not matching even my both classes in viewmodel and in model are maching
even I tried to declare my viewmodel with List<property> still the above line give same error can someone share the right code


Answers (4)