首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

EF基础1

2013-03-21 
EF基础一EF基础,从0开始:using Systemusing System.Collections.Genericusing System.Linqusing System

EF基础一

EF基础,从0开始:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.Entity;using System.ComponentModel.DataAnnotations;namespace CodeFirstNewDatabase{    class Program    {        static void Main(string[] args)        {            using (var db = new BloggingContext())            {                Console.Write("Enter a name for a new Blog: ");                var name = Console.ReadLine();                var blog = new Blog { Name = name };                db.Blogs.Add(blog);                db.SaveChanges();                var query = from b in db.Blogs                            orderby b.Name                            select b;                Console.WriteLine("All blogs in the database:");                foreach (var item in query)                {                    Console.WriteLine(item.Name);                }                Console.WriteLine("Press any key to exit...");                Console.ReadKey();            }        }    }    public class Blog    {        public int BlogID { get; set; }        public string Name { get; set; }        public string Url { get; set; }        public virtual IList<Post> Posts { get; set; }    }    public class Post    {        public int PostID { get; set; }        public string Title { get; set; }        public string Content { get; set; }        public int BlogId { get; set; }        public virtual Blog Blog { get; set; }    }    public class User    {        [Key]         // annotation: keyattribute        public string Username { get; set; }        public string Displayname { get; set; }    }    public class BloggingContext : DbContext    {                 public DbSet<Blog> Blogs { get; set; }        public DbSet<Post> Posts { get; set; }        public DbSet<User> Users { get; set; }        protected override void OnModelCreating(DbModelBuilder modelBuilder)           // fluent api: override onmodelcreating method        {            modelBuilder.Entity<User>()                .Property(u => u.Displayname)                .HasColumnName("Display_name");        }           }}


EF基础1

 

热点排行