Having some trouble with relations in Entity Framework.
I found a similar post: Entity Framework Entity w/ One-to-Many and One-to-One?
But it does not answer the question I have.
What I'm trying to accomplish is a relation between two entities which have both a One-To-Many relation AND a One-To-One/Optional.
This is the code:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Username { get; set; }
[Required]
public int GroupID { get; set; }
[ForeignKey("GroupID")]
public virtual Group Group { get; set; }
}
public class Group
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
[Required]
public int GroupAdminID { get; set; }
[ForeignKey("GroupAdminID")]
public virtual User GroupAdmin { get; set; }
[ForeignKey("UserId")]
public virtual List<User> Members { get; set; }
}
These are linked with this fluent API code:
modelBuilder.Entity<User>().HasRequired(u => u.Group).WithMany(g => g.Members);
modelBuilder.Entity<Group>().HasRequired(g => g.GroupAdmin).WithOptional();
The group can have several members, but only one admin. While a user is connected to one (and only one) group.
I'm clearly messing something up, cause in my head this should work.
If anyone can help I'd appreciate it.
Regards, Robin