끊임없이 정진. 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 [원본 다운로드]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Fragmenta의 각서라고 할까, 그것 밖에 발견되지 않았기 때문에 시도해보기로 했습니다. 다만, 내용을 보면 어플리케이션을 만드는 프레임워크로서 사용되는 것도 의식하고 있는 것 같습니다. 하지만, 지금은 정확하지 않은 것 같기 때문에,...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.