끊임없이 정진. NET 4.0 (9) - ADO. NET Entity Framework 4.1 의 Code First

23625 단어 framework
[색인 페이지] [원본 다운로드]  
끊임없이 정진. NET 4.0 (9) - ADO. NET Entity Framework 4.1 의 Code First
저자: webabcd ADO. NET Entity Framework 4.1 의 새로운 기능 소개: Code First 예시 Web. config
<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <!--
                Persist Security Info     True,        
               Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());     Code First                 master  
        -->
        <add name="MyConnection" providerName="System.Data.SqlClient" connectionString="server=.;database=MyDB;uid=sa;pwd=111111;Persist Security Info=True" />
    </connectionStrings>
</configuration>

 
Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Data.Entity;
using EF41.CodeFirst;

namespace EF41
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            //   Code First           ,      ,   Code First            
            Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());

            //      
            // Database.SetInitializer<MyContext>(null);
        }
    }
}

 
Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EF41.CodeFirst
{
    public class Category
    {
        public string CategoryId { get; set; }
        public string Name { get; set; }
        public string Comment { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}

 
Product.cs
/*
 *                        ,        ,     ,   :Data Annotations   Fluent API
 *        Data Annotations               (   Fluent API                     MyContext.cs   )
 *     Table -               ,                 
 *     Key -        ,     Code First     “Id” “<  >Id”        ,        "int" "long" "short"  ,             identity   。 :           
 *     DatabaseGenerated -                 
 *         DatabaseGeneratedOption.None -       
 *         DatabaseGeneratedOption.Identity -    
 *         DatabaseGeneratedOption.Computed -    
 *     Required -        ,               null  
 *     MaxLength -          ,      max
 *     StringLength -          
 *     Column -                ,              Code First      
 *     NotMapped -       ,                 
 *     Timestamp -                 datetime
 *     ForeignKey -        ,                             
 *     InverseProperty -            ,                 
 *           “    ”,       Product.Category       Category.Products
 *     ComplexType -     ,            ,               ,                ,   Price.cs   
 *     Timestamp -   Code First       byte[]                timestamp   
 *     ConcurrencyCheck -                 ,    ,             Timestamp
 */

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

using System.ComponentModel.DataAnnotations;

namespace EF41.CodeFirst
{
    [Table("CategoryProduct")]
    public class Product
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int ProductId { get; set; }

        [Required]
        [MaxLength(128)] // [StringLength(128, MinimumLength = 16)]
        [Column("ProductName")]
        public string Name { get; set; }

        [NotMapped]
        public string Comment { get; set; }

        public DateTime CreateTime { get; set; }

        public Price Price { get; set; }

        [ConcurrencyCheck]
        [Timestamp]
        public byte[] TimeStamp { get; set; } 

        public string CategoryId { get; set; }

        [ForeignKey("CategoryId")]
        [InverseProperty("Products")]
        public virtual Category Category { get; set; }
    }
}

 
Price.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.ComponentModel.DataAnnotations;

namespace EF41.CodeFirst
{
    //      ,              ,   :Price_Dollar   Price_RMB,      
    [ComplexType]
    public class Price
    {
        public Price()
        {
            Dollar = null;
            RMB = null;
        }

        public decimal? Dollar { get; set; }
        public decimal? RMB { get; set; }
    }
}

 
MyContext.cs
/*
 *      EntityFramework(   4.1)
 *      System.Data.Entity
 *      System.ComponentModel.DataAnnotations
 */

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

using System.Data.Entity;

namespace EF41.CodeFirst
{
    //     Context      DbContext
    public class MyContext : DbContext
    {
        //              connectionStrings   name
        //      Context      ,    EF41.CodeFirst.MyContext
        public MyContext(string connString)
            : base(connString)
        {
            // DbContextConfiguration.LazyLoadingEnabled -         ,     true
            //     true -     (Lazy Loading):              ,              
            //     false -     (Eager loading):   Include              ,             Include        
            this.Configuration.LazyLoadingEnabled = true;

            // DbContextConfiguration.AutoDetectChangesEnabled -         ,     true
            this.Configuration.AutoDetectChangesEnabled = true;
        }

        //         Context               
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }

        //                        ,        ,     ,   :Data Annotations   Fluent API
        //        Fluent API               (   Data Annotations                     Product.cs   )
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>()
                .Property(s => s.Name)
                .IsUnicode(false) //              varchar,IsUnicode(true)   nvarchar,    nvarchar
                .IsRequired() //               
                .HasMaxLength(64); //                  64
        }
    }
}

 
Demo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.Entity;

namespace EF41.CodeFirst
{
    public partial class Demo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Code First     DbContext API         Demo
            using (var db = new MyContext("MyConnection"))
            {
                Random random = new Random();

                var category = new Category { CategoryId = Guid.NewGuid().ToString(), Name = "software " + random.Next(1, int.MaxValue) };
                db.Categories.Add(category);

                var product = new Product { Name = "windows " + random.Next(1, int.MaxValue), Category = category, CreateTime = DateTime.Now, Price = new Price() };
                var product2 = new Product { Name = "windows " + random.Next(1, int.MaxValue), Category = category, CreateTime = DateTime.Now, Price = new Price() };
                db.Products.Add(product);
                db.Products.Add(product2);

                int recordsAffected = db.SaveChanges();
                Response.Write("" + recordsAffected.ToString());


                /*
                 * DbContext API       
                 * 
                 * db.Categories.Find() -                ,          
                 * db.Categories.Add() -               
                 * db.Categories.Attach() -                
                 * db.Entry(entity).State = System.Data.EntityState.Modified -       
                 * db.Categories.AsNoTracking() -    Context   ,   NoTracking      ,     Detached   。              ,       
                 *        ,      ,         ,  IsModified = true
                 *     db.Entry(product).Property(p => p.Name).CurrentValue
                 *     db.Entry(product).Property("Name").CurrentValue
                 *     (Eager loading)   
                 *     db.Categories.Include(p => p.Products.First())
                 *     db.Categories.Include(p => p.Products)
                 *     db.Entry(product).Reference(p => p.Category).Load()
                 *    sql
                 *     db.Categories.SqlQuery("select * from Categories").ToList() //       
                 *     db.Database.SqlQuery<string>("select Name from Categories").ToList(); //       
                 *     db.Database.ExecuteSqlCommand(sql); //      sql
                 */
            }
        }
    }
}

 
OK  [원본 다운로드]

좋은 웹페이지 즐겨찾기