I'm getting a client-side error when trying to save an entity. 2 tables have a one-to-many and one-to-zero relationship at the same time and this is causing the following error:
Unable to determine the relationship represented by navigation property 'Group.LockedByUser' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating
These are my current contexts:
User entity
public class User
{
[Key]
public int UserId { get; set; }
public string Username { get; set; }
public int GroupId { get; set; }
public Group GroupThisUserBelongsTo { get; set; }
public ICollection<Group> GroupsLockedByThisUser { get; set; }
public ICollection<Config> Configs { get; set; }
}
Group entity
public class Group
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GroupId { get; set; }
public string GroupName { get; set; }
public int? LockedByUserId { get; set; }
public User LockedByUser { get; set; }
public ICollection<User> Users { get; set; }
}
DbContext1 extract
modelBuilder.Entity<Group>(entity =>
{
entity.HasOne(d => d.LockedByUser)
.WithMany(p => p.GroupsLockedByThisUser)
.HasForeignKey(d => d.LockedByUserId);
}
modelBuilder.Entity<User>(entity =>
{
entity.HasOne(d => d.GroupThisUserBelongsTo)
.WithMany(p => p.Users)
.HasForeignKey(d => d.GroupId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
Config entity
public class Config
{
[Key]
public int ConfigId { get; set; }
public int UserId { get; set; }
public string Config { get; set; }
public User User { get; set; }
}
DbContext2 extract
modelBuilder.Entity<Config>(entity =>
{
entity.HasOne(d => d.User)
.WithMany(p => p.Configs)
.HasForeignKey(d => d.UserId);
});
The piece of code generating the error is as follows:
var config = new Config {
UserId = 123456,
Config = "test"
};
_dbContext2.Config.Add(config);
_dbContext2.SaveChanges();
I really don't understand why I get a client-side error when trying to save that entity. The error isn't even from the context from which I am trying to save.
Are my foreign keys set properly?
Group
has manyUser
-User
has oneGroup
(FKGroupId
)User
locks zero or manyGroup
(FKLockedByUserId
)Config
has oneUser
(FKUserId
)