Ahojte, prosim Vas o pomoc, protoze si uz nevim rady. Delam na webove aplikaci a chci v ni vypsat data, ktera jsou ve vztahu One To Many. Vypis pouze ze OnModelCreating metody v DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//One-To-Many Information-Category
modelBuilder.Entity<Category>()
.HasMany<Information>(i => i.Informations)
.WithRequired(c => c.Category)
.HasForeignKey(f => f.IdCategory);
//Many-To-Many Article-Bunkr
modelBuilder.Entity<Article>()
.HasMany(s => s.Sections).WithMany(a => a.Articles)
.Map(t => t.MapLeftKey("IdArticle")
.MapRightKey("IdSection")
.ToTable("ArticleSection")
);
}
Tady jsou modely:
public class Information
{
public Information()
{
this.IsHidden = false;
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
public int IdInformation { get; set; }
public string TitleInformation { get; set; }
public string ContentInformation { get; set; }
public DateTime? DateCreatedInformation { get; set; }
public DateTime? DateEventInformation { get; set; }
public bool IsHidden { get; set; }
//Foreign key
public int IdCategory { get; set; }
//Navigation property
public virtual Category Category { get; set; }
}
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
public int IdCategory { get; set; }
public string NameCategory { get; set; }
//Navigation property
public virtual ICollection<Information> Informations { get; set; }
}
K memu problemu: Kdyz data necham vypsat prasacky rovnou z modelu, vse funguje, ale jelikoz se chci neco priucit, tak bych rad pouzival ViewModely, avsak nevim jak naplnit ViewModel daty v relaci z modelu, abych je nasledne mohl predat do View. Prozatim (prasacky) to mam takto:
namespace KVHTO.Areas.Admin.Controllers
{
public class InformationController : Controller
{
private KvhtoContext db = new KvhtoContext();
// GET: Admin/Information
public ActionResult Index()
{
var informations = db.Informations.ToList();
return View(informations);
}
}
}
Mohl by me nekdo, prosim, nasmerovat jak mam ta data spravne namapovat? Nejlepe manualne a pokud by to slo tak i pomoci AutoMapperu? Nejlepe nejak nakopnout? Nejspise jsem mel problem v dotazu Linq. Dekuji moc za tipy :) PS: Neda se prihlasit.
|