MVC3入门试练----模型
模型类(主外键关系)
-------SchoolType.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models { public class SchoolType { [Key] public virtual int st_id { get; set; } public virtual string st_name{get;set;} public virtual List<School> Schools { get; set; } } }
-------School.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; //需要引用的命名空间 using System.Data.Entity; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models { /// <summary> /// 模型类,School对应着数据库中的名字 /// 这个类中的属性对应着数据库里的字段名称 /// </summary> public class School { //指定主键,不要相信mvc的约定 [Key] public virtual int s_id { get; set; } public virtual int s_name { get; set; } public virtual DateTime s_date { get; set; } public virtual List<Student> Student { get; set; } //对应着SchoolType的主键 public virtual int st_id { get; set; } public virtual SchoolType SchoolType { get; set; } } }
-------Student.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace MvcApplication3.Models { public class Student { [Key] public virtual int stu_id { get; set; } public virtual int stu_name { get; set; } public virtual DateTime stu_date { get; set; } //对应着School的主键 public virtual int s_id { get; set; } public virtual School Schools { get; set; } } }
-------SchoolDBContext.cs(数据库上下文)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MvcApplication3.Models { /// <summary> /// 数据库上下文 /// 类负责在数据库中获取,存储,更新,处理 School /// </summary> public class SchoolDBContext:DbContext { public DbSet<School> Schools { get; set; } public DbSet<SchoolType> SchoolTypes { get; set; } public DbSet<Student> Students { get; set; } } }
------------容易出的错:
解决方法:
在Global.asax的 Application_Start()里面添加依据代码(清空数据库):
Database.SetInitializer(new DropCreateDatabaseAlways<MvcApplication3.Models.SchoolDBContext>());
=======================添加控制器
转载于:https://blog.51cto.com/962410314/1592014