从MVC3中的UserID获取用户名

时间:2011-06-06 08:23:09

标签: asp.net-mvc asp.net-mvc-3 entity-framework ef-code-first

我上课了:

public class Post
{
    [Key]
    public int PostID { get; set; }
    [DisplayName("Text komentáře")]
    [Required(ErrorMessage = "Je potřeba vyplnit text komentáře")]
    public string Text { get; set; }
    public DateTime PostDate { get; set; }

    public int TopicID { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }
}

和用户类:

public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public FullName Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public IIdentity Identity{ get; set; }
    public virtual Role Right { get; set; }

   public virtual ICollection<Post> Posts { get; set; }
   public virtual ICollection<Topic> Topics { get; set; }
}

主题类:

public class Topic
{
    public int TopicID { get; set; }

    [Required(ErrorMessage = "Je potřeba vyplnit titulek")]
    [DisplayName("Titulek")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Je potřeba vyplnit obsah příspěvku")]
    [DataType(DataType.MultilineText)]
    [DisplayName("Obsah článku")]
    public string Text { get; set; }

    public int UserID { get; set; }
    public virtual User User { get; set; }
    // tento atribut nám nastaví jméno atribut, které bude na stránce
    [DisplayName("Datum zveřejnění")]
    public DateTime PublishedDate { get; set; }

    public virtual ICollection<Post> Posts { get; set; }

}
控制器中的

我有这个方法来显示主题:

    public ActionResult Zobrazit(int id)
    {
        var topic = db.Topics.Find(id);
        var username = db.Users.Find(topic.UserID).UserName;
        ViewBag.UserName = username;
        return View(topic);
    }

并查看Zobrazit看起来像这样:

<div class="topicHeader">@Html.DisplayFor(model => model.Title)</div>
   <fieldset>
   <p>Autor: @Html.ActionLink((string)ViewBag.UserName, "Podrobnosti", "Uzivatel", new { id = Model.UserID }, null)
   Zasláno: @Html.DisplayFor(model => model.PublishedDate)</p>
   <p>@Html.DisplayFor(model => model.Text)</p>
   </fieldset>
@if (Model.Posts != null)
{
    foreach (SkMoravanSvitavka.Models.Post comment in Model.Posts)
    {
    @Html.Partial("_Post", comment)
    }
}
@if (Context.User.Identity.IsAuthenticated)
{
    using (Html.BeginForm("Vytvorit", "Post"))
    {
    <div id="posts">
        <input type="hidden" name="TopicID" value="@Model.TopicID" />
        @*<label for="Author">Email:</label> <input type="text" name="Author"/> *@
        <label for="Text">
            Komentář:</label>
        <br />
        <textarea name="Text" rows="5" cols="40"></textarea>
        <br />
        <input type="submit" value="Přidat komentář" />
    </div>
    }
}

最后,帖子的部分视图如下所示:

@model SkMoravanSvitavka.Models.Post
<fieldset>
<p>
Author: @Html.ActionLink((string)ViewBag.UserName, "Podrobnosti", "Uzivatel", new { id = Model.AuthorID }, null) Přidáno: @String.Format("{0:g}", Model.PostDate)
</p>
<p> 
@Model.Text
</p>  
</fieldset>

我的问题是我在数据库中为每个帖子保存了UserID,我可以在控制器中获取主题(假设我有论坛)并且我在ViewBag中“发送”它但我不知道如何获取用户名在部分视图中从UserID发布。谢谢你的帮助

修改 我在Eranga帖子中进行了更改(添加公共虚拟用户用户,添加模型构建器,...),但现在我有重新创建数据库的问题。在VS中有错误:

The database creation succeeded, but the creation of the database objects did not. See inner exception for more details.

然后YSOD:

System.Data.SqlServerCe.SqlCeException: The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = Topic_User ]

EDIT2: 我更改了帖子,主题和用户的类,两者都在原帖中显示,在这里我添加了数据库上下文:

public class TeamContext : DbContext
{
    public DbSet<Player> Players { get; set; }
    public DbSet<Team> Teams { get; set; }
    public DbSet<New> News { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Topic> Topics { get; set; }
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>().HasRequired(p => p.User)
            .WithMany(u => u.Posts)
            .HasForeignKey(p => p.UserID);
        modelBuilder.Entity<Topic>().HasRequired(t => t.User)
            .WithMany(u => u.Topics)
            .HasForeignKey(t => t.UserID);
    }
  }

2 个答案:

答案 0 :(得分:1)

由于您的UserID模型中有Post属性,您应该可以执行以下操作:

@Html.ActionLink(Model.UserID, "Podrobnosti", "Uzivatel" ...

希望这有帮助!

<强>更新 对不起,我没看好你的帖子。如果您在User课程中添加Post属性,则可以从部分视图访问该媒体资源,如下所示:

@Html.ActionLink(Model.User.Username, "Podrobnosti", "Uzivatel" ...

答案 1 :(得分:1)

你可以这样做。

将User属性添加到Post类

public class Post
{
   //all other fields
   public int UserID { get; set; }
   public User User { get; set; }
}

public class User
{
   //all other fields
   public int UserID { get; set; }
   public virtual ICollection<Post> Posts { get; set; }
}

然后通过包含关系来构建模型

modelBuilder.Entity<Post>().HasRequired(p => p.User)
                .WithMany(u => u.Posts)
                .HasForeignKey(p => p.UserID);

然后,您可以访问Post对象中的UserName属性。

确保您急切加载“主题”类的“帖子”属性和“帖子”类的“用户”属性