2

I have a model in my mvc 5 website, I use database first approach. In some tables I have more than one columns referencing the same table. When the data model scaffolds, it appends numbers to the relationship names, is there a way I can give it a defined name so I can understand what each column is used for from within the code. Check below to see a screenshot of one of the occurrences.

The model

In the above, the MainContactPerson and ContactStaffId both map to the same table - Employee, so it created the relationships Employee and Employee1.

In Code

In my code, I access it like that above.

NOW WHAT I WANT. Can I rename those relationship names to something like MainContact and ContactStaff so I do something like below in my code.

 var client = _db.Organisation.FirstOrDefault();

 var mainContactPerson = client.MainContact;
 var contactPerson = client.ContactStaff;
Mordecai
  • 397
  • 4
  • 17
  • It would be better to add the EF version (presumably 6.*something*) as a tag + the .NET Framework version, and also remove `asp.net` and `asp.net-mvc` and `model-view-controller` because those are UI layer tags that have no relation to the problem at hand. – Peter B Oct 12 '20 at 11:00
  • since im struggling with same issue +1 – Jochem Van Hespen Oct 12 '20 at 12:37

1 Answers1

0

I'm sad to see no answers here, as I've also been annoyed by that very naming issue. I've generally just dealt with whatever the model gives me, but you're correct that the default naming of myfield and myfield1 is, at the very least, non-intuitive.

But since I'm working on a new project I'm going to try an "alias" property with the intuitive name in a partial class with the same name and namespace as the model class. In my DB project I've added an "Extensions" folder to hold these partial classes, but keep the same namespace as the generated model. I've used partial entity classes for other data-layer functionality like audit trail and common access methods, which lets me add stuff to the model without losing it when I delete and regenerate the model. (MySQL's migration support was not all there originally so I delete and regen for each migration.) When it's working I'll be back with a code sample.

William T. Mallard
  • 1,562
  • 2
  • 25
  • 33