Display Name
Display Name

Reputation: 15111

What is the foreign key if more than one pair of navigation properties exists?

The following is quoted from the official documentation.

You can use the Data Annotations to configure how navigation properties on the dependent and principal entities pair up. This is typically done when there is more than one pair of navigation properties between two entity types.

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int AuthorUserId { get; set; }
    public User Author { get; set; }

    public int ContributorUserId { get; set; }
    public User Contributor { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [InverseProperty("Author")]
    public List<Post> AuthoredPosts { get; set; }

    [InverseProperty("Contributor")]
    public List<Post> ContributedToPosts { get; set; }
}

Question

As I am new to EF Core, what is the foreign key if more than one pair of navigation properties exist?

Upvotes: 1

Views: 92

Answers (1)

Wijitha
Wijitha

Reputation: 1389

Your code would work in this way,

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    [ForeignKey("Author")]
    public int AuthorUserId { get; set; }
    public virtual User Author { get; set; }

    [ForeignKey("Contributor")]
    public int ContributorUserId { get; set; }
    public virtual User Contributor { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [InverseProperty("Author")]
    public ICollection<Post> AuthoredPosts { get; set; }

    [InverseProperty("Contributor")]
    public ICollection<Post> ContributedToPosts { get; set; }
}

Cheers,

Upvotes: 1

Related Questions