简体   繁体   中英

Entity Framework Invalid column name when adding property that is not in db table

I had decided that there are just too many things that need to be different on the View Presentation Layer compared to what is actually in the database table.

I have a class of properties in C# that represents the model of my database HOWEVER I was reading about ViewModels and I can see how they can do the nice things of not displaying containing an unnecessary amount of data that you do not wish to display on your view, and it can also be an important aggregrate of combining multiple models in which you have much more available to you for trickling down to the View.

I simply tried to add a class with a property

  public class ExtendedFile
  {
     public string FileSize { get; set; }
  }

Then I figured I could simple add this as another property to my other model class , so I added it

public ExtendedFile ExtendedFile { get; set; }

Then it seems that I can in my controller simply hydrate this

 file.ExtendedFile.FileSize = ConvertFileSize(file.size);

So then my View now has

<td>@item.ExtendedFile.FileSize</td>

Well that did not work out .. A controller method had code in it in which a linq query that joins 2 tables freaked out. The error message is:

Invalid column name 'ExtendedFile_FileSize'.

The code that causes the error is:

var query = (
    from qtips in dbProd.tblTips 
    where qtips.id == 30 
    join files in dbProd.tblFiles on qtips.id.ToString() 
    equals files.@group select new { qtips, files }).ToList();

在非数据库列的属性上将属性添加为[NotMapped]

Thanks to Stephen while I realize that I "can" do use this other model, I'm just going really against the proper patterns in which what a true ViewModel is for

Thus I already had this working 40 minutes ago by simply adding the [NotMapped]

[NotMapped]
public ExtendedFile ExtendedFile { get; set; }

It exposes a bigger issue of the fact that I was not understanding the ViewModel.

So while that "works" I am going to instead have a ViewModel with

  1. The properties I want to display from the tblFiles class
  2. The properties from this this ExtendedFile class such as

     public class ExtendedFile { public string FileSize { get; set; } //more properties } 

This means that it can not find a field of the database that defined in the model.

For example, my problem was that I had written the "Connection string" with the test database wrong.

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