[RESOLVED]View with multiple tables

Hello,

I have two tables in my database that have similar data but not same.

I’d like to show these tables in the same view. Looking in internet the most suggested practice is to use a ViewModel class.

So… These are my class tables:

iCareIndoorAlert.cs

    [Table("iCareIndoorAlerts")]
    public class iCareIndoorAlert
    {
        [Key]
        [DisplayName("ID Allarme iCare indoor")]
        public long AlertID { get; set; }

        [DisplayName("ID Messaggio")]
        public long MessageID { get; set; }

        public string UUID { get; set; }

        public int MAG { get; set; }

        public int MIN { get; set; }

        [DisplayName("Distanza")]
        public float Dist { get; set; }

        [DisplayName("Data ora")]
        public DateTime DateTime { get; set; }

        public virtual HttpPop3 HttpPop3 { get; set; }
    }

iCareOutdoorAlert.cs

    [Table("iCareOutdoorAlerts")]
    public class iCareOutdoorAlert
    {
        [Key]
        [DisplayName("ID Allarme iCare outdoor")]
        public long AlertID { get; set; }

        [DisplayName("ID Messaggio")]
        public long MessageID { get; set; }

        [DisplayName("Latitudine")]
        public float Lat { get; set; }

        [DisplayName("Longitudine")]
        public float Lon { get; set; }

        [DisplayName("Accuracy")]
        public float Acc { get; set; }

        [DisplayName("Data ora")]
        public DateTime DateTime { get; set; }
    }

After I created a ViewModel folder with a iCareAlertViewModel.cs class:

        public List<iCareIndoorAlert> iCareIndoorAlert { get; set; }
        public List<iCareOutdoorAlert> iCareOutdoorAlert { get; set; }

And added there rows in the iCareEntities.cs:

        public DbSet<iCareIndoorAlert> iCareIndoorAlerts { get; set; }

        public DbSet<iCareOutdoorAlert> iCareOutdoorAlerts { get; set; }

        public DbSet<iCareAlertViewModel> iCareAlertsViewModels { get; set; }

After I generated the iCareAlertController.cs and run the view Index.cshtml but I get the error "Key not found". So in the ViewModel I added a dummy variable with [Key] attribute and now a get an error that says that can’t find the iCareAlertViewModel table…

What am I doing wrong?

Thank you

Chen Yiyi

public DbSet<iCareAlertViewModel> iCareAlertsViewModels { get; set; }

Your ViewModel is not a database table. Hence you should add it to your entities.

Also I recommend your ViewModel to include only those properties that need to show on the view. If need you can duplicate part of the iCareIndoorAlert and iCareOutdoorAlert.

Leave a Reply