SqlServer資料庫
1.DB First
現有DB,生成edmx檔案
貼一下生成的model
//------------------------------------------------------------------------------
// <auto-generated>
// 此代碼已從模闆生成。
//
// 手動更改此檔案可能導緻應用程式出現意外的行為。
// 如果重新生成代碼,将覆寫對此檔案的手動更改。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Ruanmou.EFDBFirst
{
using System;
using System.Collections.Generic;
public partial class JD_Commodity_001
{
public int Id { get; set; }
public Nullable<long> ProductId { get; set; }
public Nullable<int> CategoryId { get; set; }
public string Title { get; set; }
public Nullable<decimal> Price { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
}
}
2.Code First
有資料庫,從資料庫獲得model,就是這個
貼一下生成的Model,和DB First的不太一樣,長度attribute加上了
[Table("JD_Commodity_001")]//1 特性
public partial class JDCommodity001
{
[Key]
public int Id { get; set; }
public long? ProductId { get; set; }
//[ForeignKey]
[Column("CategoryId")]
public int? ClassId { get; set; }
[StringLength(500)]
public string Title { get; set; }
public decimal? Price { get; set; }
[StringLength(1000)]
public string Url { get; set; }
[StringLength(1000)]
public string ImageUrl { get; set; }
}
如果資料庫字段或表名和model的不一樣(比如想去掉下劃線)可以有3種方式,方式1見上圖,Model上或屬性上加attribute
方式2在 OnModelCreating 裡添加映射,code first 的 OnModelCreating 和DB first的不一樣, db 的什麼也沒寫,截圖下code first的OnModelCreating
代碼,啟動時可以完成資料庫和代碼結構的同步
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//啟動時可以完成資料庫和代碼結構的同步
//new CreateDatabaseIfNotExists<codeFirstDbContext>();//預設 不存在就建立
//new DropCreateDatabaseAlways<codeFirstDbContext>();//每次都删除重建
//new DropCreateDatabaseIfModelChanges<codeFirstDbContext>();
//Database.SetInitializer<codeFirstDbContext>(new DropCreateDatabaseIfModelChanges<codeFirstDbContext>());
//對不起 資料都沒了。。 測試/快速部署 其實這裡還可以完成資料初始化
//請一定小心
modelBuilder.Entity<JDCommodity002>()
.ToTable("JD_Commodity_002")
.Property(c => c.ClassId)
.HasColumnName("CategoryId");//2 鍊式API
modelBuilder.Configurations.Add(new JDCommodity003Mapping());//3 映射檔案
modelBuilder.Entity<Category>()
.Property(e => e.Code)
.IsUnicode(false);
方式3 Mapping 的方式,寫個Mapping 檔案,上面的代碼有,據說沒什麼人用
Oracle資料庫
可能引用這個就可以用吧
DB first , OnModelCreating 什麼也沒寫 model還是沒有長度的attribute
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
這個是EF5
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
模型管理器管理外鍵,因為名字不一樣看着不開心,全改成FK 開頭的了用Powerdesigner改的,擷取的更新,