MVC实现模型优先编码之连接数据库

来源:互联网 发布:网络电视能看直播吗 编辑:程序博客网 时间:2024/05/13 13:24

一:在Models下建立模型

如:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcLiuYan.Models
{
    public class User
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage="请输入Email")]
        [DataType(DataType.EmailAddress)]
        [DisplayName("账号")]
        [MaxLength(255)]
        public string Email { get; set; }

        [Required(ErrorMessage="请输入用户名")]
        [DisplayName("用户名")]
        [MaxLength(10,ErrorMessage="用户名不得超过10个字符")]
        public string Name { get; set; }

        [Required(ErrorMessage = "请输入联系方式")]
        [DisplayName("电话")]
       
        [DataType(DataType.PhoneNumber)]
        public string Tel { get; set; }

        [Required(ErrorMessage = "请输入密码")]
        [DisplayName("密码")]
        [MaxLength(32, ErrorMessage = "用户名不得超过32个字符")]
        [DataType(DataType.Password)]
        public string Pwd { get; set; }

        [Required(ErrorMessage = "请输入地址")]
        [DisplayName("住址")]
        [MaxLength(255, ErrorMessage = "用户名不得超过255个字符")]
        public string Address { get; set; }

        [Required(ErrorMessage = "请输入年龄")]
        [DisplayName("年龄")]
        [Range(0,200,ErrorMessage="年龄必须介于0~200之间")]
       
        public int Age { get; set; }

        [Required(ErrorMessage = "选择性别")]
        [DisplayName("性别")]
      
        public int Sex { get; set; }

        public ICollection<LiuYan> LiuYans { get; set; }

    }
}

二:在web.xml文件中添加数据库连接字符串

如(vs2012自带的连接字符串):

<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcLiuYan-20140813090420;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcLiuYan-20140813090420.mdf" />
  </connectionStrings>

三:在Models下新建DbContext类:

如下:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MvcLiuYan.Models
{
    public class MvcLiuYanContext:DbContext
    {
        public MvcLiuYanContext()
            : base("DefaultConnection")//指向的是Web.xml中的链接字符串的name值
        {
       
        }
        public DbSet<LiuYan> LiuYans { get; set; }

        public DbSet<Replay> Replays { get; set; }

        public DbSet<User> Users { get; set; }//指向用户模型
    }
}

 

0 0