Hello Guys, Hope everyone is doing well. First, I would like to thank everyone for contributing to this forum, I am new to ASP.NET Core and here people helped me a lot to solve my problems, I was having a problem to set foreign key in my database and I posted
the issue here which got solved but it lead me to a new problem so I decided to make a separate thread for it in a relevant category.
Okay so, I have three classes, Dinghy, Manufacturer and ClassAssociation, each Dinghy have 1 manufacturer and 1 class association and so each table of Dinghy includes its respective foreign keys for manufacturer and class association. The problem is that,
when I add Dingies to database through a form, everything works well and table of Dinghies receives the IDs of Manufacturer and Class Association, but when I proceed to display the name of Manufacturer and Class Association using the foreign keys, it shows
null. Debugging has shown me that the object of Manufacturer and Class Association is storing null. Why is it so when I have properly configured the foreign keys?
I am attaching the relevant code for you guys to dig out the issue.
.CSHTML File (I am using this syntax to display the data)
<td>
@Html.DisplayFor(modelItem => item.Manufacturers.Manufacturer)</td><td>
@Html.DisplayFor(modelItem => item.CA.CAName)</td>
ListDinghies Action in Controller
public async Task<IActionResult>ListDinghies(){returnView(await _context2.Dinghies.ToListAsync());}
AddDinghies Post Action in Controller
public async Task<IActionResult>AddDinghies([Bind("id,Name,OlympicBoat,Type,TypeCrew,TypePurpose,Length,Beam,Draft,SailAreaUpwind,GennakerSailArea,SpinnakerSailArea,SAOptional,SAOptional2,Weight,PYS,ImagePath,CrewPersons,CrewWeight,Description,DesignBy,DesignYear,OlympicSectionViewSwitch,ManufacturerID,ClassAssociationID")]Dinghies dg){if(ModelState.IsValid){//_context2.Manufacturers.Include(e => e.Manufacturer).FirstOrDefault(m => m.id == );
_context2.Add(dg);
await _context2.SaveChangesAsync();returnRedirectToAction(nameof(Index));}returnView(dg);}
Dinghies.cs (Only showing section where foreign keys and navigation properties are added)
[ForeignKey("Manufacturers")]publicintManufacturerID{get;set;}publicManufacturersManufacturers{get;set;}[ForeignKey("CA")]publicintClassAssociationID{get;set;}public CA CA {get;set;}
I have searched a lot on internet but couldn't find the solution, I believe only an expert can figure out the problem. Thanks