Foreign Key between Models with ef
Hi, I have an API in .net and I'm trying to link the property PackageTebexId from the model UserPackage to the property TebexId from the model Package but I can't achieve to do it. It always bind PackageTebexId to the Id of the model Package.
Here's my models :
User.cs
UserPackage.cs
Package.cs
EntityBase.cs
And here's my DbContext
NewSkyDbContext.cs
8 Replies
i'm not sure what you're asking makes sense
foreign keys point to other entities/rows in another table, not a single piece of information
the correct way to do this is simply access
UserPackage.Package.TebexId
, you don't need to "link" anything elsewhat I'm trying to do is to link the table Package to the table UserPackages like that, when I take my User, I can retrieve also their packages.
Like this
User user = await _userRepository.Query().Include(x => x.Packages).ThenInclude(x => x.Package);
It's been a year i didn't touch to a .Net API so maybe my thoughts are wrong.all you need for this is the
public Package Package { get; set; }
in UserPackage
you don't even need to configure the relationship manuallyok ty, will try it
i don't know what you're trying to do with the tebex id, that seems like a property of a package and not the primary key of any of your entities
The TebexId is the Id of the package I retrieved of an other application. but I can't set it to the primary key because of the "IDENTITY_INSERT" that are enabled
that forgive me to create package with a custom id in my db
right, foreign keys should be using the primary keys of your entities
not random keys you got somewhere else
ok mb
ok i change a bit the logic like you said and it work well, ty