I have a model that looks like this
public class Issue
{
public Guid Id { get; set; }
[Required]
public User ReportedByUser { get; set; }
public User ClosedByUser { get; set; }
public Category Category { get; set; }
}
However, when I run ef migrations add <MigrationName>
I am getting the following error:
The navigation 'ReportedByUser' on entity type 'WebProject.Models.Issue' has not been added to the model, or ignored, or target entityType ignored.
I do not get this error when I only have 1 navigational property of type User
in the model. How do I make this work with the model above?
It will better for you to explicitly declare the foreign keys properties when you do code first with migrations. Also if you stick to the convention ReferencePropertyName + Id for this property, you do not have to decorate the class with ForeignKeyAttribute as EF will resolve it for you.
public class Issue
{
public Guid Id { get; set; }
public Guid ReportedByUserId { get; set; }
public User ReportedByUser { get; set; }
public Guid ClosedByUserId { get; set; }
public User ClosedByUser { get; set; }
}
I was able to fix this by setting up the following relationships in my DbContext.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Issue>()
.HasOne(i => i.ReportedByUser)
.WithMany(u => u.Issues)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Issue>()
.HasOne(i => i.ClosedByUser)
.WithMany(u => u.Issues)
.OnDelete(DeleteBehavior.Restrict).IsRequired(false);
base.OnModelCreating(modelBuilder);
}
And setting up the model like below.
public class Issue
{
public Guid Id { get; set; }
[Required]
public User ReportedByUser { get; set; }
public User ClosedByUser { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With