MVC CodeFirst 学习心得

原文链接: http://www.cnblogs.com/zhanghonjiang2011/archive/2012/04/25/2469679.html

这几天都在学习MVC 的 Code First, 在国内的网站上找到案例不是很满意,于是就跑到微软官网  看 CodeFirst 方面的文章,我那个去啊 ,看着英文头都大了 , 还好咱有google翻译,一遍揣测,一边翻译。经过两天的艰苦奋斗,算是对CodeFirst 小有了解。

MVC 下有3种开发模式:DataBase First,Model First以及Code First。

DataBase First :从数据库自动生成的模型文件,基于xml格式,包括概念模型和存储模型以及两者之间的映射。

Model First:从数据库生成模型或者是空模型中,添加实体->添加属性->根据模型生成数据库->把生成的数据库脚本执行。

CodeFirst:指的是先用C#/VB.NET 创建的类定义模型,然后根据模型映射到现有的数据库或生成数据库结构。

另外CodeFirst 支持Data Annotations [相当于数据注释] 以及 Fluent API;

下面简单的介绍下EF 支持的Annotations类型

View Code
 1 1、KeyAttribute 
 2 
 3 2、StringLengthAttribute 
 4 
 5 3、MaxLengthAttribute 
 6 
 7 4、ConcurrencyCheckAttribute 
 8 
 9 5、RequiredAttribute 
10 
11 6、TimestampAttribute 
12 
13 7、ComplexTypeAttribute 
14 
15 8、ColumnAttribute       Placed on a property to specify the column name, ordinal & data type 
16 
17 9、TableAttribute       Placed on a class to specify the table name and schema 
18 
19 10、InversePropertyAttribute       Placed on a navigation property to specify the property that represents the other end of a relationship 
20 
21 11、ForeignKeyAttribute       Placed on a navigation property to specify the property that represents the foreign key of the relationship 
22 
23 12、DatabaseGeneratedAttribute       Placed on a property to specify how the database generates a value for the property (Identity, Computed or None) 
24 
25 13、NotMappedAttribute       Placed on a property or class to exclude it from the database


接下来正式的介绍CodeFirst 案例

1、新建solution->更名为CodeFirstDemo

2、在solution下建立MVC Application

3、在Models 文件夹下建立一个类, 命名为BlogClasses,移除BlogClasses类,并在里面添加Blog,Post,Comment类

扫描二维码关注公众号,回复: 6770650 查看本文章
View Code
 1     public class Blog
 2     {
 3         public int Id { get; set; }
 4         [Required]
 5         public string Title { get; set; }
 6         public string BloggerName { get; set; }
 7         public string Test { get; set; }
 8         public virtual ICollection<Post> Posts { get; set; }
 9     }
10 
11     public class Post
12     {
13         public int Id { get; set; }
14         public string Title { get; set; }
15         public DateTime DateCreated { get; set; }
16         public string Content { get; set; }
17         public int BlogId { get; set; }
18         public ICollection<Comment> Comtents { get; set; }
19     }
20 
21     public class Comment
22     {
23         public int Id { get; set; }
24         public DateTime DateCreated { get; set; }
25         public string Content { get; set; }
26         public int PostId { get; set; }
27         public Post Post { get; set; }
28     }
29 
30     public class Supplier
31     {
32         [Key]
33         public string SupplierCode { get; set; }
34         public string Name { get; set; }
35     }

注意:代码里面的Data Annotations 需要引入命名空间 System.ComponentModel.DataAnnotations;

紧接着在Models 里面建立类BlogContext

View Code
 1 public class BlogContext : DbContext
 2     {
 3         public DbSet<Blog> Blogs { get; set; }
 4         public DbSet<Post> Posts { get; set; }
 5         public DbSet<Comment> Comments { get; set; }
 6         public DbSet<Supplier> Suppliers { get; set; }
 7 
 8         public class BlogContextInitializer : DropCreateDatabaseIfModelChanges<BlogContext>
 9         {
10             protected override void Seed(BlogContext context)
11             {
12                 base.Seed(context);
13             }
14         }
15 
16         protected override void OnModelCreating(DbModelBuilder modelBuilder)
17         {
18             modelBuilder.Entity<Blog>().Property(s => s.Title).IsRequired();
19             base.OnModelCreating(modelBuilder);
20         }
21     }

这个类派生于DbContext ,这个比较关键,模型生成数据库主要就是依靠此类。里面有类中类 。

这样可以随意更改模型,生成相应的数据表和字段。实现这个的前提是:需要在主程序入口上加上如下一句代码就万事ok了

System.Data.Entity.Database.SetInitializer(new BlogContext.BlogContextInitializer());

之后就是在Controller里面写逻辑代码了

创建一个Controller命名为BlogController,从简考虑,里面只有添加、删除,修改等功能。

View Code
 1     public class BlogController : Controller
 2     {
 3         //
 4         // GET: /Blog/
 5 
 6         public ActionResult Index()
 7         {
 8             using (var db = new BlogContext())
 9             {
10                 return View(db.Blogs.ToList());
11             }
12         }
13 
14         public ActionResult Create()
15         {
16             return View();
17         }
18 
19         [HttpPost]
20         public ActionResult Create(Blog blog)
21         {
22             if (ModelState.IsValid)
23             {
24                 using (var db = new BlogContext())
25                 {
26                     db.Blogs.Add(blog);
27                     db.SaveChanges();
28                 }
29                 return RedirectToAction("Index");
30             }
31             else
32             {
33                 ModelState.AddModelError("","内容不能为空!");
34             }
35             return View();
36         }
37     }

最后生成View ,浏览就行了。

 

转载于:https://www.cnblogs.com/zhanghonjiang2011/archive/2012/04/25/2469679.html

猜你喜欢

转载自blog.csdn.net/weixin_30699831/article/details/94800029
今日推荐