码迷,mamicode.com
首页 > Windows程序 > 详细

C#博客随笔之九:EF框架的使用

时间:2015-05-18 22:26:34      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

这一章主要介绍EF的使用:

关于EF的获取在上一章中已经给出了

现在需要创建一个AppModelContext

[DbConfigurationType(typeof(MysqlDbConfiguration))]
    public partial class AppModelContext : IdentityDbContext<ApplicationUser, CustomIdentityRole, Guid, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        static AppModelContext()
        {

        }
        public static AppModelContext Create()
        {
            return new AppModelContext();
        }
        public AppModelContext()
            : base("Name=db")
        {


        }

public DbSet<Vote> Votes { get; set; }
 public void SetDebugOutput()
        {
            this.Database.Log = (s) => Debug.WriteLine(s);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ApplicationUser>().Property(p => p.PasswordHash).HasMaxLength(200);
            modelBuilder.Entity<ApplicationUser>().Property(p => p.SecurityStamp).HasMaxLength(200);
            modelBuilder.Entity<ApplicationUser>().Property(p => p.PhoneNumber).HasMaxLength(50);
            modelBuilder.Entity<CustomIdentityRole>().Property(p => p.Name).HasMaxLength(128);
            modelBuilder.Entity<ApplicationUser>().Property(p => p.UserName).HasMaxLength(128);

          

        }

其中

public DbSet<Link> Links { get; set; }

这段代码是用来创建数据表的,数据表的结构在 Link类中创建

关于Link类中的内容:

 

 public class Link
    {
        [Key]
        public int Id { get; set; }
        [StringLength(50)]
        [Display(Name="标题")]
        public string Title { get; set; }
        [StringLength(500)]
        [Url]
        [Display(Name="链接")]
        public string Url { get; set; }
        public LinkType Type { get; set; }
        public int SchoolId { get; set; }
        public LinkState LinkState { get; set; }
        public virtual ApplicationUser User { get; set; }
        public Guid UserId { get; set; }
       // public LinkType Type { get; set; }
        public int TypeId { get; set; }
    }

  

其中包含主键[Key]   字符串长度[StringLength(50)]    过滤规则[Url]   以及 显示名称 [Display(Name="标题")]

public virtual ApplicationUser User { get; set; }
        public Guid UserId { get; set; }

是用来定义外键

在定义完表结构之后

我们将内容添加到Context中,然后在Package Manager Console 中输入 Enable-Migration

然后系统会自动生成Migration文件夹,然后输入 add-migration Name

再输入Update-database  就可以更新数据库,以后每次更改表结构都要add-migration Name 然后Update-database之后 就可以更新表结构,但是如果表中有数据又添加了不可为空的字段,是会报错的。

使用EF可以将类直接映射成表结构,也可以将数据库的数据直接加载到对象当中,代码出错率会大幅度降低,代码修改成本也会大幅度降低,EF是一个非常优秀的框架

C#博客随笔之九:EF框架的使用

标签:

原文地址:http://www.cnblogs.com/MelodyWang/p/4512962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!