Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple navigation properties of the same type in EF7

Tags:

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?

like image 911
hyde Avatar asked Mar 16 '16 18:03

hyde


2 Answers

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; }    
}
like image 200
E-Bat Avatar answered Oct 12 '22 11:10

E-Bat


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; }    
}
like image 21
hyde Avatar answered Oct 12 '22 10:10

hyde