✅ Multiple one to many relationships

I've just recently started using ASP.NET and I ran into a bit of a wall Basically:
public class Reserva
{
public int Id { get; set; }

public string ClienteId { get; set; }
public ApplicationUser Cliente { get; set; }

public string FuncionarioId { get; set; }
public ApplicationUser Funcionario { get; set; }
}

public class ApplicationUser : IdentityUser
{
public Empresa? Empresa { get; set; }
public ICollection<Reserva> Reservas { get; set; }
public ICollection<Reserva> EntregasRecolhas { get; set; }

}
public class Reserva
{
public int Id { get; set; }

public string ClienteId { get; set; }
public ApplicationUser Cliente { get; set; }

public string FuncionarioId { get; set; }
public ApplicationUser Funcionario { get; set; }
}

public class ApplicationUser : IdentityUser
{
public Empresa? Empresa { get; set; }
public ICollection<Reserva> Reservas { get; set; }
public ICollection<Reserva> EntregasRecolhas { get; set; }

}
How do I make a migration of this? I'm getting "Unable to determine the relationship represented by navigation 'ApplicationUser.EntregasRecolhas' of type 'ICollection<Reserva>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'." And I don't know how to proceed without having to manually do it ( which I don't know how to do it either )
5 Replies
Saber
Saber2y ago
because you have 2 different relationships, you need to configure which collection relates to which of those properties. https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#manual-configuration
Relationships - EF Core
How to configure relationships between entity types when using Entity Framework Core
Marcoelho97
Marcoelho97OP2y ago
OH! I had been trying to figure out where to put the manual part but I thought it was in the migrations, which wasn't a solution for me cause my teachers will want to delete them! That makes a lot of sense! Thank you! Another question, though: In the example you showed me:
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts);
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts);
How does it know that the "WithMany" will be "b.Posts"? Mine autofilled as well, but I don't understand how it knows, considering that it only mentioned the class Post, not the class Blog
Angius
Angius2y ago
.HasOne(p => p.Blog) returns something that contains the information about what type the p.Blog is Then, .WithMany(b => b.Posts) uses that information, that type is the b there
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.
Marcoelho97
Marcoelho97OP2y ago
I see, that makes a lot of sense! Thank you so much!!! ♥
Want results from more Discord servers?
Add your server