Reputation: 1602
I have an ApplicationUser
and a Group
:
public class ApplicationUser : IdentityUser
{
public int? AdminInGroupId { get; set; }
public int? UserInGroupId { get; set; }
public Group AdminInGroup { get; set; }
public Group UserInGroup { get; set; }
// some more properties
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string GroupAdminId { get; set; }
public ApplicationUser GroupAdmin { get; set; }
public List<ApplicationUser> GroupUsers { get; set; }
}
This is my OnModelCreating()
configuration for Group
(I don't have one for ApplicationUser
):
modelBuilder.Entity<Group>()
.HasOne(a => a.GroupAdmin)
.WithOne(g => g.AdminInGroup)
.HasForeignKey<ApplicationUser>(a => a.AdminInGroupId);
modelBuilder.Entity<Group>()
.HasMany(u => u.GroupUsers)
.WithOne(g => g.UserInGroup)
.OnDelete(DeleteBehavior.NoAction);
When running the query below, I'm not getting the GroupAdmin
:
Group group = await db.Groups
.Include(a => a.GroupAdmin)
.Include(u => u.GroupUsers)
.Where(m => m.Id == id)
.FirstOrDefaultAsync();
Notice how GroupAdmin
is null
, while GroupAdminId
has a value.
Upvotes: 0
Views: 46
Reputation: 433
I Can't understand your database design, why you have one to one and one to many relations in one table. Please check my code may be better for your project.
public class ApplicationUser : IdentityUser
{
public int? GroupId { get; set; }
public Group Group { get; set; }
// some more properties
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public GroupType GroupType { get; set; }
public List<ApplicationUser> Users { get; set; }
}
public enum GroupType
{
AdminGroup = 0 ,
UserGroup = 1 ,
BothGroup = 2
}
Upvotes: 2