0

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();

enter image description here

Notice how GroupAdmin is null, while GroupAdminId has a value.

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.