MVC代码第一:自己的模型和SimpleMembership用户之间的一对多关系 [英] MVC Code First: One-to-many relationship between own model and SimpleMembership user
问题描述
我目前正在一个活动日历网站上工作,而对ASP.NET来说,我还是一个新手。我正在使用MVC4框架,以及MVC4模板附带的EntityFramework(CodeFirst)和SimpleMembershipProvider。我也使用迁移 - 如果这是从任何兴趣。
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.
我目前有两种模式,一对多关系,工作正常:
I do currently have two models, with a one-to-many relationship, which work just fine:
_Events.cs (不得不命名这样,因为事件被保留)
_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; }
}
我非常感谢你提前提供任何帮助。 / p>
I would like to thank you very much for any help in advance.
推荐答案
您需要在您的评论中拥有UserId。
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; }
}
这篇关于MVC代码第一:自己的模型和SimpleMembership用户之间的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!