C
C#13mo ago
BakaPresident

❔ Entity Framework not required foreign key as required?

I'm currently using ASP.Net Identity as my user scaffold. My user currently looks like
public class User : IdentityUser
{
// Add additional data here
public string DisplayName { get; set; }

public ICollection<Bookshelf> Bookshelfs { get; } = new List<Bookshelf>();
}
public class User : IdentityUser
{
// Add additional data here
public string DisplayName { get; set; }

public ICollection<Bookshelf> Bookshelfs { get; } = new List<Bookshelf>();
}
I've added UserGenre and Genre like this.
public class Genre
{
public int Id { get; set; }
[Required]
public string Name { get; set; }

public List<UserGenre> UserGenres { get; } = new();
}
public class Genre
{
public int Id { get; set; }
[Required]
public string Name { get; set; }

public List<UserGenre> UserGenres { get; } = new();
}
public class UserGenre
{
public int Id { get; set; }

public string UserId { get; set; }
public User User { get; set; } = null!;

public int GenreId { get; set; }
public Genre Genre { get; set; } = null!;
}
public class UserGenre
{
public int Id { get; set; }

public string UserId { get; set; }
public User User { get; set; } = null!;

public int GenreId { get; set; }
public Genre Genre { get; set; } = null!;
}
5 Replies
BakaPresident
BakaPresident13mo ago
To clarify, the database is indeed linked with foreign key constraint. However, what puzzles me is why UserId in the table is placed as nullable, however, Genre is not nullable. I wanted both to be non nullable but it doesn't seem to work in my way that i intended? I could force it to be [Required] which should fulfil my requirement but is that okay?
Tvde1
Tvde113mo ago
Using [Required] is okay 👍
BakaPresident
BakaPresident13mo ago
Okay thanks! i'll stick with [Required] just weird that null!; works on Genre but not User
TravestyOfCode
TravestyOfCode13mo ago
Would that be due to GenreId being an int and therefore can not be null and not the = null!, where as UserId is a string which can be null?
Accord
Accord13mo 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