JoJo
JoJo

Reputation: 99

EF6 Multiple foreign keys for ApplicationUser Error

I'm pretty new to Entity Framework and the code first approach and I'm stuck. Sorry if it's a dumb question.

I found some questions around here that look the same, but I get an other error then the ones other people get and I would love to solve it without the need to add other parameters if possible.

So Basically, I have my ApplicationUser(load in from Identity) that looks like this:

public class ApplicationUser : IdentityUser
{
    public virtual Province Provincie { get; set; }

    [ForeignKey("From")]
    public virtual ICollection<Message> SentMessages { get; set; }

    [ForeignKey("To")]
    public virtual ICollection<Message> ReceivedMessages { get; set; }


}

And I have a Message Class that looks like:

public class Message
{
    [Key]
    public int ID { get; set; }
    public virtual ApplicationUser From { get; set; }
    public virtual ApplicationUser To { get; set; }
    public String MessageContent { get; set; }
    public DateTime Date { get; set; }
}

Now, when I try to add a migration i get the following error:

The ForeignKeyAttribute on property 'ReceivedMessages' on type 'EF_CF_Basics.Models.ApplicationUser' is not valid. The foreign key name 'To' was not found on the dependent type 'EF_CF_Basics.Models.Message'. The Name value should be a comma separated list of foreign key property names.

So actually, visual studio tells me it can't find the To in Message, but it is really there.

Upvotes: 0

Views: 423

Answers (1)

Slauma
Slauma

Reputation: 177153

You probably want to use [InverseProperty("From")] instead of [ForeignKey("From")] and [InverseProperty("To")] instead of [ForeignKey("To")]. Foreign key properties must be scalars (int, string, Guid, etc.) but your From and To properties are actually entities, i.e. they are navigation properties.

Upvotes: 2

Related Questions