John Mayer
John Mayer

Reputation: 3363

Foreign key to the same table in EF - Getting an error

Basically I got the following table:

    [Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    [Required]
    public string UserName { get; set; }
    [Required]
    public string AffiliateId { get; set; }
    [ForeignKey("UserId")]
    public UserProfile Referer { get; set; }
}

Which has a foreign key to itself (Referer). The issue is however the fact that when I try to insert a new row:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new { AffiliateId = affiliateId, Referer = referer });

The variable "referer" here is an actual UserProfile. I get the following error: No mapping exists from object type UserProfile to a known managed provider native type.

What am I doing wrong?

Upvotes: 0

Views: 1408

Answers (2)

Myk Willis
Myk Willis

Reputation: 12879

I assume that you are trying to reference a different UserProfile object as the referrer, in which case you don't want to use your primary key (UserId) as the value passed to a ForeignKey attribute. Instead, you should either declare another int property to serve as the FK for the Referrer object, and use ForeignKey to tell EF to use that as the FK for the Referer navigation property, or simply don't use ForeignKey at all and let EF generate the key column for you:

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    // ...
    public UserProfile Referer { get; set; } // EF will generate Referer_UserId
}

(The ForeignKey attribute is used to tell entity framework how to match up a navigation property with the corresponding FK column - it's not used to identify the primary key of the referenced object).

Now, that being said, I'm not sure that's causing your present error:

No mapping exists from object type UserProfile to a known managed provider native type.

Check to be sure that there is a DbSet<UserProfile> UserProfiles defined inside the DbContext object in AccountModels.cs. And if your UserProfile object actually refers to any other types that you didn't show in your sample code above, be sure there is a DbSet<> for those as well.

Upvotes: 1

Allan
Allan

Reputation: 469

Because you are passing the profile, should the syntax not be referer.UserId ?

Upvotes: 0

Related Questions