У меня есть сообщение класса:
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>
Моя проблема в том, что у меня в базе данных для каждого сообщения сохраняется идентификатор пользователя, и я могу получить его в контроллере для темы (скажем, у меня есть форум), и я «отправляю» его во ViewBag, но я не знаю, как получить имя пользователя в частичном представлении для сообщения от UserID. Спасибо за помощь
Edit:
Я внес изменения, которые были в посте 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);
}
}