EF--DB First

  DB First先有數據庫,根據數據庫生成Model實體對象。數據庫

一、新建數據庫表,Poet,Poem,Meter.關係以下:框架

  

 

  建表語句ide

create table Poet
(
    PoetId int identity(1,1) primary key,
    FirstName varchar(20),
    MiddleName varchar(20),
    LastName varchar(20)
)


create table Meter
(
    MeterId int identity(1,1) primary key,
    MeterName varchar(50) 
)

create table Poem
(
    poemId int identity(1,1) primary key,
    PoetId int,
    MeterId int,
    Title varchar(50),
    foreign key(PoetId) references poet(Poetid),
    foreign key(MeterId) references Meter(MeterId)
)

create view vwLibrary
as
select  poet.FirstName,poet.MiddleName,poet.LastName,poem.Title,Meter.MeterName from Meter ,poet,Poem where Meter.MeterId=poem.MeterId and poem.PoetId=poet.PoetId
View Code

二、新建控制檯項目DBFirstDemo,肯定。spa

三、點擊選中項目添加-->新建-->選擇數據模板-->ADO.NET實體數據模型,肯定。3d

  

四、實體模型嚮導選擇從數據庫生成,下一步。code

  

五、選擇或者新建連接,鏈接選擇後繼續下一步。對象

  

六、選擇框架版本,本機選擇6.0blog

  

七、選擇數據庫對象,選擇表和視圖。並勾選下方複選框。ip

  

八、生成實體圖上展現以下:ci

  

九、使用實體,修改Main方法以下:

  

static void Main(string[] args)
        {
            using (var context = new EF6RecipesEntities())
            {
                var poet = new poet { FirstName = "John", LastName = "Milton" };
                var poem = new Poem { Title = "Paradis Lost" };
                var meter = new Meter { MeterName = "Iambic Pentameter" };

                poem.poet = poet;
                poem.Meter = meter;

                context.Poems.Add(poem);

                poem = new Poem { Title="Paradis Regained" };
                poem.poet = poet;
                poem.Meter = meter;

                context.Poems.Add(poem);

                poet = new poet { FirstName = "Lewis", LastName = "Carroll" };
                poem = new Poem { Title = "The Hunting of the Shark" };
                meter = new Meter { MeterName = "Anapestic Tetrameter" };
                poem.Meter = meter;
                poem.poet = poet;
                context.Poems.Add(poem);
                poet = new poet { FirstName = "Lord", LastName = "Byron" };
                poem = new Poem { Title = "Don Juan" };
                poem.Meter = meter;
                poem.poet = poet;
                context.Poems.Add(poem);
                context.SaveChanges();


                Console.WriteLine("----------------讀取Poet----------------");

                var poets = context.poets;

                foreach (var poettemp in poets)
                {
                    Console.WriteLine("{0}{1}", poettemp.FirstName, poettemp.LastName);
                    foreach (var poemtemp in poet.Poems)
                    {
                        Console.WriteLine("\t{0} ({1})", poemtemp.Title, poemtemp.Meter.MeterName);
                    }
                }

                Console.ReadKey();
            }
        }
View Code

十、執行結果

  

 

總結:DBFirst是根據現有數據庫生成Model實體,並對實體進行後續操做,適用舊項目改造。

相關文章
相關標籤/搜索