Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show display values for a foreign key property in a model

I have a model that looks kinda like this:

public class Notes
{
public int NoteID {get; set;}
public string Note {get; set;}
public int CustomerID {get; set;}
{

On the Notes Details view, I would like to be able to show Customer Name instead of CustomerID. Obviously if this were a Create or Edit view I use a dropdown list. However I am not sure how to show the value and not the ID in a read only Details view.

Thanks!

like image 906
Ryan Avatar asked Feb 20 '23 12:02

Ryan


1 Answers

Code First is mainly... code, not Database logic.

So, instead of having the Foreign Keys (like CustomerID) in your models (it's also possible, and sometimes needed, but not always), you'll be more confortable having a reference property

public virtual Customer Customer {get;set;}

So in your view having Notes as Model, you could simply use

@Html.DisplayFor(m => m.Customer.Name);

When you retrieve your Notes entity, don't forget to include the related entities / properties needed for your View / ViewModel (I let you read about lazy loading)

like image 134
Raphaël Althaus Avatar answered Feb 23 '23 03:02

Raphaël Althaus