EF--DB First

  DB First先有数据库,根据数据库生成Model实体对象。

1、新建数据库表,Poet,Poem,Meter.关系如下:

  

 

  建表语句

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

2、新建控制台项目DBFirstDemo,确定。

3、点击选中项目添加-->新建-->选择数据模板-->ADO.NET实体数据模型,确定。

  

4、实体模型向导选择从数据库生成,下一步。

  

5、选择或者新建链接,连接选择后继续下一步。

  

6、选择框架版本,本机选择6.0

  

7、选择数据库对象,选择表和视图。并勾选下方复选框。

  

8、生成实体图上展示如下:

  

9、使用实体,修改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

10、执行结果

  

 

总结:DBFirst是根据现有数据库生成Model实体,并对实体进行后续操作,适用旧项目改造。

 

posted @ 2017-07-19 06:11  mopheify  阅读(227)  评论(0编辑  收藏  举报