0

Following the ForeignKey docs, and multiple examples online I was under the influence that if I give my property (foreign key) this attribute, it would get replaced in a Html.Display call by the first textual property of the parent table.

This doesn't happen and all I get is the same foreign key field.

Does this work in db first applications, and if so, how do I make it work (using ForeignKey)?

Thanks.

EDIT: Or is this Scaffolding exclusive behaviour?

UPDATE: Example code:

// Entity model in Case.cs
public partial class Case
{
public int ID {get; set;}
public string Description {get; set;}
public int Classification_ID {get; set;}

public virtual Classification Classification {get; set;}
}

// Entity model in Classification.cs
// It's a lookup table
public partial class Classification
{
public int ID {get; set;}
public string Label {get; set;}
}

// File with partials
[MetadataType(typeof(CaseMetadata))]
public partial class {} 

public class CaseMetadata
{
[ForeignKey("Classification")]
public int Classification_ID {get; set;}
}
Savo Pejović
  • 133
  • 1
  • 9
  • And what does your code looks like? Can't tell you what's wrong if I don't see anything. It's suppose to work like your exemples. – Antoine Pelletier Feb 06 '19 at 14:51
  • @AntoinePelletier It looks very much like one in the example. So this works with db first? Also I saw I was actually using MVC 4 instead of 5, so I will have to check later if this was the issue. – Savo Pejović Feb 06 '19 at 16:39
  • With db first you should use partial classes anyway... – Antoine Pelletier Feb 06 '19 at 17:00
  • @AntoinePelletier Yeah, I am. Partial classes and Metadata classes. – Savo Pejović Feb 06 '19 at 17:41
  • Probably there's something wrong in your MetaDatas... Can you show it ? – Antoine Pelletier Feb 06 '19 at 18:01
  • @AntoinePelletier Added an example. – Savo Pejović Feb 06 '19 at 23:06
  • So, there is no `[DisplayColumn("NameOfTheColumn")]` in your class ? That's pretty much how you let EF knows WHICH column is for display... – Antoine Pelletier Feb 07 '19 at 14:16
  • @AntoinePelletier I have used that attribute already on the parent table class, but it didn't work. I didn't mention it because ForeignKey attribute should get the first string field in the parent (see [docs](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displaycolumnattribute?view=netframework-4.7.2)) , which doesn't happen. So, the problem happens before choosing which field to display. Thanks for trying to help. – Savo Pejović Feb 07 '19 at 18:09
  • And how do you display your property in the view (considering you are using MVC) you should use `@Html.DisplayFor( t => t.????????)` Because `@Html.Dsiplay` rarely does what you want – Antoine Pelletier Feb 07 '19 at 18:12
  • @AntoinePelletier Already tried both ways. – Savo Pejović Feb 08 '19 at 07:51

0 Answers0