0

I'd like to create a Review entity so users can review and rate a user (profile) entity for my social site. But the problem I'm having is when trying to insert a review into the table I get an exception; something about a foreign key conflicting with ProfileId in the Profile table. So I'm not sure if the syntax is correct here for creating the entities and their relationships?

Here is my code

public class Profile 
{
    public virtual ICollection<Review> Reviews { get; set; }    // one to many
}

public class Review
{
    [Key]
    public int ReviewId { get; set; }

    public int ProfileRefId { get; set; }

    // one-to-many here
    [ForeignKey("ProfileRefId")]
    public virtual Profile Profile { get; set; }

    public DateTime Created { get; set; }
    public string body {get; set; }
    public int Rating {get; set; }

    // here is where I want to set the reviewer to a user (profile entity), 
    //   but not sure about the syntax
    [ForeignKey("ReviewerProfile ")]
    public int ProfileId { get; set; }

    public virtual Profile ReviewerProfile { get; set; }
}

When I try to insert here is what I do.

var reviewer = dbContext.Profiles.Where(i => i.ApplicationUserId == userId).First();
Review reviewer = new Review
                      {
                          Created = DateTime.Now,
                          ReviewerProfile = reviewer
                      };

profile.Reviewers.Add(reviewer);

// then save...
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • doesn't anyone have any input here! this seems like a simple problem that has occurred before, surely I'm not the first who has needed this! – chuckd Aug 09 '17 at 04:18
  • You have two references to `Profile` table in `Review` class: `public virtual Profile Profile { get; set; }` & `public virtual Profile ReviewerProfile { get; set; }`. Choose one which you want to keep & set `ForeignKeyAttribute` to its PK field. – Tetsuya Yamamoto Aug 09 '17 at 04:22
  • You are not updating `reviewer.Profile` – Frank Fajardo Aug 09 '17 at 04:26
  • I'm not sure what you guys mean, can you please further explain your comments? – chuckd Aug 09 '17 at 04:29
  • this link here https://stackoverflow.com/questions/28570916/defining-multiple-foreign-key-for-the-same-table-in-entity-framework-code-first gave me the answer I needed. – chuckd Aug 09 '17 at 05:23

0 Answers0