查询多对多关系表到实体MVC

时间:2017-12-30 21:31:59

标签: model-view-controller

我有很多关系表。 Sube和用户

namespace Odev.Entities
    {
    public class User
    {
    [Key]
    public int Id { get; set; }
    [Required]
    [DisplayName("Kimlik No")]

    [ StringLength(11)]
    [Index(IsUnique = true)]
    public string UserName { get; set; }

    [ StringLength(8)]
    [DisplayName("Şifre")]
    public string Password { get; set; }

    [DisplayName("Ad Soyad")]
    public string NameSurname { get; set; }

    [DisplayName("Bölüm")]
    public string Bolum { get; set; }

    [DisplayName("Dal")]
    public string Dal  { get; set; }

    [DisplayName("Öğrenci No")]
    public int OgrenciNo { get; set; }

    public int RoleId { get; set; }
    public virtual ICollection<Sube> Subes { get; set; }
    public virtual List<Notification> Notifications { get; set; }
    public virtual List<Homework> Homeworks { get; set; }
    public  virtual Role Role { get; set; }
   }
}

namespace Odev.Entities
   {
   public class Sube
   {
   [Key]
   public int Id { get; set; }

   [DisplayName("Şube")]

   public string Sube_Name { get; set; }
   public virtual Homework Homework { get; set; }
   public  virtual ICollection<User> Users { get; set; }
   }
}

namespace Odev.DataAccessLayer
   {
   public class DatabaseContext : DbContext
   {
   public DatabaseContext() : base("dataConnection")
   {
      Database.SetInitializer(new OdevInitializer());
   } 
   public DbSet<User> Users { get; set; }
   public DbSet<Homework> Homeworks { get; set; }
   public DbSet<Role> Roles { get; set; }
   public DbSet<Sube> Subes { get; set; }
   public DbSet<Notification> Notifications { get; set; }

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
   }
}    
}

和我的ViewModel

namespace Odev.Models{ 
public class ViewModel{ 
public string Sube_Name { get; set; }
public string NameSurname { get; set; }
public string UserName { get; set; }
public int UserId { get; set; }
public int SubeId { get; set; }
public User User { get; set; }
public Sube Sube { get; set; }
public Role Role { get; set; }
}}

我想显示用户的SubeId:

enter image description here

我如何选择Sube的ID?

1 个答案:

答案 0 :(得分:0)

您需要使用外键连接两个实体。 请阅读此文档:Creating a More Complex Data Model for an ASP.NET MVC Application