C
C#2y ago
balloman

✅ How Do I Save a New Fully Defined Relationship in EF Core?

Ok, so if I have a token which looks like this
/// <summary>
/// Represents a token for a device
/// </summary>
public class Token
{
/// <summary>
/// The actual token
/// </summary>
public required string TokenId { get; set; }
/// <summary>
/// The user the token belongs to
/// </summary>
public required User User { get; set; }
}
/// <summary>
/// Represents a token for a device
/// </summary>
public class Token
{
/// <summary>
/// The actual token
/// </summary>
public required string TokenId { get; set; }
/// <summary>
/// The user the token belongs to
/// </summary>
public required User User { get; set; }
}
and I have a user
public class User
{
public required string UserId { get; set; }
public required List<Token> Tokens { get; set; }
}
public class User
{
public required string UserId { get; set; }
public required List<Token> Tokens { get; set; }
}
How do I create a new token if the user doesn't exist?
13 Replies
Saber
Saber2y ago
create the token and the user?
balloman
balloman2y ago
So when creating the token how do I define the user?
phaseshift
phaseshift2y ago
Why is user property in token required?
balloman
balloman2y ago
Yeah good point maybe it’s not needed
Tvde1
Tvde12y ago
What have you tried so far? Should be as simple as adding the token instance to the user's token list and saving the context
balloman
balloman2y ago
I haven’t tried it yet I’ve been busy with work but if I add the token to the users token list how do I set the user on the token If the user didn’t previously exist
phaseshift
phaseshift2y ago
Need to make a user first.
balloman
balloman2y ago
So when I make the user, then I just set the token list to empty?
phaseshift
phaseshift2y ago
You don't need to set it to anything, but yes
balloman
balloman2y ago
It's required
phaseshift
phaseshift2y ago
Making navigation properties required does not seem like a good idea to me I'm not sure how modern EF Core deals with it, though
balloman
balloman2y ago
So it ended up working fine by setting the list to empty
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts