I have a 2 tables with multiple columns that points to one entity or table.
[Table("opcr")]
public class Opcr
{
[Key]
public int Id { get; set; }
[Required]
public string? Title { get; set; }
[Required]
public string DepartmentHeadId { get; set; }
[ForeignKey(nameof(DepartmentHeadId))]
public ApplicationUser DepartmentHead { get; set; }
[Required]
public string EvaluatedById { get; set; }
[ForeignKey(nameof(EvaluatedById))]
public ApplicationUser EvaluatedBy { get; set; }
[Required]
public string ReviewedById { get; set; }
[ForeignKey(nameof(ReviewedById))]
public ApplicationUser ReviewedBy { get; set; }
}
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
namespace LGU_HR.Models;
public class ApplicationUser : IdentityUser
{
[Required]
[MaxLength(50)]
public string? FirstName { get; set; }
[Required]
[MaxLength(50)]
public string? LastName { get; set; }
// if I uncomment this, I'll get an error
// public ICollection<Opcr> DepartmentHead { get; }
// public ICollection<Opcr> EvaluatedBy { get; }
// public ICollection<Opcr>? ReviewedBy { get; }
}
I want this connection so I can search the OPCR
table through users. This is a one-to-many relationship, but when I uncomment DepartmentHead
on ApplicationUser
, I get this error:
Unable to create a 'DbContext' of type ''. The exception 'Unable to determine the relationship represented by navigation 'ApplicationUser.DepartmentHead' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.' was thrown while attempting to create an instance. For the different patterns supported at design time
I've read this documentation but they don't have this example.
Can someone explain this situation? Not sure where am I wrong.
I think that is because you did not stick to naming conventions, which in case of collection should be just plural name Opcrs
- in your case that's not possible of course, as property names must be unique.
Moreover, try to think how EF would know which collection corresponds to which foreign key in Opcr
? That's ambiguous.
You would need to define that relation explicitly, for example:
modelBuilder.Entity<ApplicationUser>()
.HasMany(u => u.DepartmentHead)
.WithOne(o => o.DepartmentHead)
Analogically, with other properties.
Reference: Fluent API relationships