MVC Code First: One-to-many relationship between own model and SimpleMembership user

sfey picture sfey · Aug 19, 2013 · Viewed 9k times · Source

I am currently working on an event calendar website and I am still a novice when it comes to ASP.NET. I am using the MVC4 Framework, as well as the EntityFramework (CodeFirst) and the SimpleMembershipProvider, which comes with the MVC4 template. I am also using Migrations - If that is from any interest.

What I've got so far

I do currently have two models, with a one-to-many relationship, which work just fine:

_Events.cs (had to name it that way, because event is reserved)

public class _Event
{
    public int _EventId { get; set; }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public virtual List<Comment> comments { get; set; }
}

Comment.cs

public class Comment
{
    public int CommentId { get; set; }
    public string Text { get; set; }

    public int _EventId { get; set; }
    public virtual _Event _Event { get; set; }
}

The problem

Now, I would like to add another one-to-many relationship between Comment and the User from the Membership model, but can't seem to figure out how to do so.

The goal I would like to archieve is, that I can have a list of commments for each event and print out the user information for each comment. I tried several things, but could not get it to work yet. My last attempt looks like this:

public class Comment
{
    // snip - see above

    public virtual UserProfile User { get; set; }
}

I would like to thank you very much for any help in advance.

Answer

Xaxum picture Xaxum · Aug 19, 2013

You need to have UserId in your Comments as so.

public class Comment
{
    // snip - see above

    public int UserId {get; set;}
    public virtual UserProfile User { get; set; }
}

You will also need to set the relationship between your Comment and your User so in your account controller have something like this.

public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }
    }