I have many to one relationship defined within my model: Project.CreatedBy = ApplicationUser.Id:
class Project{
[Required]
public ApplicationUser CreatedBy {get; set;}
}
With mapping:
modelBuilder.Entity<Project>().HasOptional(i => i.CreatedBy).WithOptionalDependent().WillCascadeOnDelete(false);
Unfortunatelly, when I try to retrieve all users from DbContext by:
var users = context.Users;
Generated SQL looks like:
SELECT
[...]
FROM [dbo].[AspNetUsers] AS [Extent1]
LEFT OUTER JOIN [dbo].[Projects] AS [Extent4] ON ([Extent4].[CreatedBy_Id] IS NOT NULL) AND ([Extent1].[Id] = [Extent4].[CreatedBy_Id])
So when certain user have created 10 projects, the user entity is multiplied 10 times. It makes me impossible to look for that user by his username:
context.Users.Single(u => u.Username == "test")
because it would give me Sequence contains more than one element exception.
Do you have any idea how to avoid that extra join?
I suspect it has something to do with modelBuilder declaration. I've been googling about this, but never found any solution.
Any materials about modelBuilder and defining relationships with it would be really appreciated too.
The mapping...
modelBuilder.Entity<Project>()
.HasOptional(i => i.CreatedBy)
.WithOptionalDependent()
...expresses this as a 1:1 association, not the 1:n association you intend it to be.
So change the mapping into one-to-many:
modelBuilder.Entity<Project>()
.HasOptional(p => p.CreatedBy)
.WithMany()
.HasForeignKey(p => p.CreatedBy_Id);
I'm not sure why EF joins in the Project
when you query User
because the association is optional), but a proper 1:n mapping will stop this.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments