一共3个表,做连表查询 USER,DEPT,USERTYPE
三个实体类如下
- C# code
public class USER { [Key] public int USERID { get; set; } public string NAME { get; set; } public string DEPTID{ get; set; } public string TYPEID{ get; set; } public virtual DEPT depts { get; set; } public virtual USERTYPE usertypes{ get; set; } }public class DEPT { [Key] public string DEPTID{ get; set; } public string NAME{ get; set; } public virtual ICollection<USER> users { get; set; } }public class USERTYPE { [Key] public string TYPEID{ get; set; } public string NAME{ get; set; } public virtual ICollection<USER> users { get; set; } }
对应关系:
- C# code
public class USERDB:DbContext { public DbSet<USER> users { get; set; } public DbSet<DEPT> depts { get; set; } public DbSet<USERTYPE> usertypes{ get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<USER>() .HasRequired(u => u.depts) .WithMany(d => d.users) .HasForeignKey(a => a.DEPTID) .WillCascadeOnDelete(false); modelBuilder.Entity<USER>() .HasRequired(u => u.usertypes) .WithMany(t => t.users) .HasForeignKey(a => a.TYPEID) .WillCascadeOnDelete(false); } }
控制器:
- C# code
public ActionResult TestList() { var db=new USERDB(); var users = db.users.ToList(); return View(users); }
前台代码:
- HTML code
@model IEnumerable<testlist.Models.USER>@foreach (var item in Model) { <tr> <td> @item.ID </td> <td> @item.NAME </td> <td> @item.depts.NAME //<--------这里报错 </td><td> @item.usertypes.NAME </td> <td>
我想显示的结果:
ID 姓名 部门名称 人员类别
但是却显示不出来,提示“未将对象引用设置到对象的实例”,是哪里代码出错了??新手,请指教,谢谢。
------解决方案--------------------------------------------------------
看看当前用户对应的部门在部门表中有数据吗?
------解决方案--------------------------------------------------------
@item.depts!=null?@item.depts.NAME:string.Empty--格式我不太清楚,意思就这样